Spring Boot Application 兩種啟動方式分析
Spring Boot Application 兩種啟動方式分析
問題:
Spring boot一般我們都會有
public static void main(String[] args) {
SpringApplication.run(xxx.class, args);
}
但是如果我們使用war包的方式,這個去掉可以嗎?
解決過程:
帶著這個問題,看了看Spring Boot的文件
在Convert an Existing Application to Spring Boot
一節中,說到了如何把Spring Mvc轉換成Spring Boot的應用。
其中有:
Once the war file is working, you can make it executable by adding a main method to your Application, as shown in the following example:
public static void main(String[] args) { SpringApplication.run(Application.class, args); }
這段話也說明了如果使用war的包,是可以不加main函式的。
總結:
-
使用main的方式很直接,就是直接拿SpringApplication進行run。
-
使用war方式啟動原理如下:
這裡涉及到兩個東西:
-
SpringBootServletInitializer 這個類實現了
WebApplicationInitializer
,代替了傳統的web.xml
配置,進行配置。在WebApplicationInitializer
的註釋裡說到:Implementations of this SPI will be detected automatically by SpringServletContainerInitializer, which itself is bootstrapped automatically by any Servlet 3.0 container
說明只要繼承了SpringBootServletInitializer會被當成servlet configuration掃描到並且執行
onStartup
方法。
看SpringBootServletInitializer
進行Application的build和run. -
@SpringApplication這個註解是一個啟動配置的註解。相當於@Configuration, @EnableAutoConfiguration和@ComponentScan。
-