特別說明: tomcat版本必須7以上,我之前就是項目main方法運行一切正常,但把war包部署到tomcat6上,訪問就報404找不到請求的路徑。
第 1 步:將這個 Spring Boot 項目的打包方式設置爲 war。
<packaging>war</packaging>
這裏還要多說一句, SpringBoot 默認有內嵌的 tomcat 模塊,因此,我們要把這一部分排除掉。
即:我們在 spring-boot-starter-web 裏面排除了 spring-boot-starter-tomcat ,但是我們爲了在本機測試方便,我們還要引入它,所以我們這樣寫:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<!-- 打包部署到tomcat上面時,不需要打包tmocat相關的jar包,否則會引起jar包衝突 -->
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
第 2 步:提供一個 SpringBootServletInitializer 子類,並覆蓋它的 configure 方法。我們可以把應用的主類改爲繼承 SpringBootServletInitializer。或者另外寫一個類。
@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
注意:部署到 tomcat 以後,訪問這個項目的時候,須要帶上這個項目的 war 包名。
另外,我們還可以使用 war 插件來定義打包以後的 war 包名稱,以免 maven 爲我們默認地起了一個帶版本號的 war 包名稱。例如:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<warName>springboot</warName>
</configuration>
</plugin>
例如:
http://localhost:8080/springboot/user/18
其中,springboot 是我放在 tomcat 上的 war 包名。