当我们需要将spring boot应用部署至外部tomcat(或其他web容器)时,相关配置需作如下调整。
1.通过spring-boot-maven-plugin插件指定启动类,该类详见第3步。
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>com.sam.demo.bootstrap.AppStart</mainClass>
</configuration>
</plugin>
2.为了正常编译,需在pom.xml文件中引入spring-boot-starter-tomcat和spring-boot-starter-tomcat,绑定到provided,同时在spring-boot-starter-web中排除tomcat依赖。最终生成的war包不包含任何与tomcat有关的jar包。可以将生成的war包部署至任何支持java web的容器中。
<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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-servlet-api</artifactId>
<version>7.0.68</version>
<scope>provided</scope>
</dependency>
3.修改spring-boot-maven-plugin插件指定的启动类。不再以main方法启动项目,而是通过SpringApplicationBuilder来指定启动类。
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
@SpringBootApplication
public class AppStart extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(AppStart.class);
}
}
附:因为项目中不再有web.xml文件,所以在eclipse中会有错误提示。解决办法是在pom.xml中加入maven-war-plugin插件。如下:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>