從Spring遷移到Spring Bootjava
Spring Boot給咱們的開發提供了一系列的便利,因此咱們可能會但願將老的Spring 項目轉換爲新的Spring Boot項目,本篇文章將會探討如何操做。web
請注意,Spring Boot並非取代Spring,它只是添加了一些自動配置的東西,從而讓Spring程序更快更好
要想添加Spring Boot,最簡單的辦法就是添加Spring Boot Starters。spring
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.2.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent>
每個Spring Boot程序都須要一個應用程序入口,一般是一個使用@SpringBootApplication註解的main程序:springboot
@SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
@SpringBootApplication註解是下列註解的組合:mvc
@Configuration ,@EnableAutoConfiguration,@ComponentScan 。app
默認狀況下@SpringBootApplication會掃描本package和子package的全部類。因此通常來講SpringBootApplication會放在頂層包下面。jsp
Spring Boot一般使用自動配置,可是咱們也能夠手動Import現有的java配置或者xml配置。spring-boot
對於現有的配置,咱們有兩個選項,一是將這些配置移動到主Application同一級包或者子包下面,方便自動掃描。
二是顯式導入。spa
咱們看一下怎麼顯示導入:code
@SpringBootApplication @ComponentScan(basePackages="com.flydean.config") @Import(UserRepository.class) public class Application { //... }
若是是xml文件,你也能夠這樣使用@ImportResource導入:
@SpringBootApplication @ImportResource("applicationContext.xml") public class Application { //... }
默認狀況下Spring Boot 會查找以下的資源地址:
/resources /public /static /META-INF/resources
想要遷移的話 咱們能夠遷移現有資源到上訴的資源地址,也可使用下面的方法:
spring.resources.static-locations=classpath:/images/,classpath:/jsp/
Spring Boot 會在以下的地方查找application.properties或者application.yml 文件:
* 當前目錄 * 當前目錄的/config子目錄 * 在classpath中的/config目錄 * classpath root
咱們能夠將屬性文件移動到上面提到的路徑下面。
若是要遷移Spring Web程序,咱們須要以下幾步:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
經過Spring Boot的自動配置,會自動檢測classpath中的依賴包,從而自動開啓@EnableWebMvc,同時建立一個DispatcherServlet。
若是咱們在@Configuration類中使用了@EnableWebMvc註解,則自動配置會失效。
該自動配置同時自動配置了以下3個bean:
對於web頁面,一般再也不推薦JSP,而是使用各類模板技術來替換:Thymeleaf, Groovy, FreeMarker, Mustache。 咱們要作的就是添加以下依賴:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
template文件在/resources/templates下面。
若是咱們仍然須要是用JSP,則須要顯示配置以下:
spring.mvc.view.prefix=/WEB-INF/views/ spring.mvc.view.suffix=.jsp
更多教程請參考 flydean的博客