spring-boot项目需要部署在外部容器中的时候,spring-boot导出的war包无法再外部容器(tomcat)中运行或运行报错。

为了解决这个问题,需要移除springBoot自带的tomcat容器。

具体解决方法如下:

1.pom.xml中

        <dependency>  
            <groupId>org.springframework.boot</groupId>  
            <artifactId>spring-boot-starter-web</artifactId>  
            <!-- 排除内置容器,排除内置容器导出成war包可以让外部容器运行spring-boot项目-->  
            <exclusions>  
                <exclusion>  
                    <groupId>org.springframework.boot</groupId>  
                    <artifactId>spring-boot-starter-tomcat</artifactId>  
                </exclusion>  
            </exclusions>  
        </dependency>
        <!-- 增加servlet-api依赖 -->
        <dependency>  
            <groupId>javax.servlet</groupId>  
            <artifactId>javax.servlet-api</artifactId>  
        </dependency>  

2.实现SpringBootServletInitializer接口

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;

public class Application extends SpringBootServletInitializer{
    
    public static void main(String[] args) {
        SpringApplication.run(Application.class);
    }
    
     @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        // 注意这里要指向原先用main方法执行的Application启动类
        return builder.sources(Application.class);
    }
}