最近一段時間一直在研究和學習springboot,感覺其十分便利好用。以前使用spring搭建項目都整好多繁瑣的配置,使用了springboot后這些繁瑣的配置統統都不要了。但就是對springboot部署的方式感覺有點不爽,還是比較喜歡打包成war來進行部署。
在spring中有這樣一個類:org.springframework.web.SpringServletContainerInitializer,閱讀該類的注釋發現該類的作用是使用編程方式的替代web.xml的。其原理就在於該類位於spring-web-xxx.jar中的META-INF/services有一個遵照java spi規范的文件,在支持servlet 3以上版本的j2ee容器中會讀取該SPI服務的實現類SpringServletContainerInitializer。springboot已經為我們擴展了該類SpringBootServletInitializer,但是該類是一個抽象類,抽象類無法被實例化因此我們需要創建一個類並繼承該類。
1 package com.torlight; 2 3 import org.slf4j.Logger; 4 import org.slf4j.LoggerFactory; 5 import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 6 import org.springframework.boot.autoconfigure.SpringBootApplication; 7 import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; 8 import org.springframework.boot.web.support.SpringBootServletInitializer; 9 import org.springframework.core.Ordered; 10 import org.springframework.core.annotation.Order; 11 12 import javax.servlet.ServletContext; 13 import javax.servlet.ServletException; 14 15 /** 16 * Created by acer on 2017-05-24. 17 * {@code TorlightSpringBootServletInitializer}繼承於SpringBootServletInitializer 被 SpringServletContainerInitializer 18 * 使用 19 * @author acer 20 * @since 2017.05.24 21 */ 22 @Order(Ordered.HIGHEST_PRECEDENCE+9999) 23 @SpringBootApplication 24 @EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class}) 25 public class TorlightSpringBootServletInitializer extends SpringBootServletInitializer{ 26 27 private static final Logger logger= LoggerFactory.getLogger(TorlightSpringBootServletInitializer.class); 28 29 @Override 30 public void onStartup(ServletContext servletContext) throws ServletException { 31 if(logger.isInfoEnabled()){ 32 logger.info("TorlightSpringBootServletInitializer is startup"); 33 } 34 super.onStartup(servletContext); 35 } 36 }
將pom.xml文件中packaging由jar改成war
由於打包成war獨立部署,將spring-boot-starter-tomcat 的范圍改成provided
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
移除spring-boot-maven-plugin maven插件
<!--
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin> -->
將靜態文件按照war中的規范存放到webapp目錄
完成上面的步驟后,執行maven打包命令將輸出的war部署j2ee容器中