springboot應用war包部署tomcat
阿新 • • 發佈:2019-01-02
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,如下:
4、新增對servlet API的依賴
5、繼承
* deploying it. If you prefer to run an embedded container then you won't need this at
* all. 如果我們構建的是wai包並部署到外部tomcat則需要使用它,如果使用內建servlet容器則不需要,外接tomcat環境的配置需要這個類的configure方法來指定初始化資源。
<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方法來指定初始化資源。
@SpringBootApplication
// mapper 介面類掃描包配置
public class Application extends SpringBootServletInitializer{
public static void main(String[] args) throws IOException {
// 程式啟動入口
Properties properties = new Properties();
InputStream in = Application.class.getClassLoader().getResourceAsStream("app.properties");
properties.load(in);
SpringApplication app = new SpringApplication(Application.class);
app.setDefaultProperties(properties);
app.run(args);
/*EmbeddedServletContainerAutoConfiguration*/
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
// TODO Auto-generated method stub
builder.sources(this.getClass());
return super.configure(builder);
}
經過以上配置,我們把構建好的war包拷到tomcat的webapp下,啟動tomcat就可以訪問啦