springboot的應用打包默認是打成jar包,并且如果是web應用的話,默認使用內置的tomcat充當servlet容器,但畢竟內置的tomcat有時候并不滿足我們的需求,如有時候我們想集群或者其他一些特性優化配置,因此我們需要把springboot的jar應用打包成war包,并能夠在外部tomcat中運行。
很多人會疑問,你直接打成war包并部署到tomcat的webapp下不就行了么?No,springboot的如果在類路徑下有tomcat相關類文件,就會以內置tomcat啟動的方式,經過你把war包扔到外置的tomcat的webapp文件下啟動springBoot應用也無事于補。
要把springboot應用轉至外部tomcat的操作主要有以下三點:
1、把pom.xml文件中打包結果由jar改成war,如下:
- <modelVersion>4.0.0</modelVersion>
- <groupId>spring-boot-panminlan-mybatis-test</groupId>
- <artifactId>mybatis-test</artifactId>
- <packaging>war</packaging>
- <version>0.0.1-SNAPSHOT</version>
2、添加maven的war打包插件如下:并且給war包起一個名字,tomcat部署后的訪問路徑會需要,如:http:localhost:8080/myweb/****
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-war-plugin</artifactId>
- <configuration>
- <warSourceExcludes>src/main/resources/**</warSourceExcludes>
- <warName>myweb</warName>
- </configuration>
- </plugin>
3、排除org.springframework.boot依賴中的tomcat內置容器,這是很重要的一步
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- <exclusions>
- <exclusion>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-tomcat</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
4、添加對servlet API的依賴
- <dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>javax.servlet-api</artifactId>
- </dependency>
5、繼承SpringBootServletInitializer
,并覆蓋它的 configure
方法,如下圖代碼,為什么需要提供這樣一個SpringBootServletInitializer子類并覆蓋它的config方法呢,我們看下該類原代碼的注釋:
/**Note that a WebApplicationInitializer is only needed if you are building a war file and
* deploying it. If you prefer to run an embedded container then you won't need this at
* all.
如果我們構建的是wai包并部署到外部tomcat則需要使用它,如果使用內置servlet容器則不需要,外置tomcat環境的配置需要這個類的configure方法來指定初始化資源。
//@ServletComponentScan
public class JobManagementApplication extends SpringBootServletInitializer{
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(JobManagementApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(JobManagementApplication.class, args);
}
}
經過以上配置,我們把構建好的war包拷到tomcat的webapp下,啟動tomcat就可以訪問啦