1.将Application启动类所在的module中的pom文件,把<packaging>标签批改成

<packaging>war</packaging>

2.移除自带内置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>

3.增加servlet依赖

<dependency>    <groupId>javax.servlet</groupId>    <artifactId>javax.servlet-api</artifactId>    <scope>provided</scope></dependency>

4.减少war的启动类

class WarStarterApplication extends SpringBootServletInitializer {    @Override    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {        //  指向Application这个springboot启动类        return builder.sources(Application.class);    }}

实现以上步骤后,应用maven的package性能打包即能放到tomcat中运行。

此时,如果想在我的项目中持续应用启动类运行我的项目,会呈现“ Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean.”报错,但在tomcat中是能失常运行的。

2021-08-30 11:00:05 ERROR SpringApplication:858 - Application run failedorg.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.context.ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean.    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:157)    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:142)    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775)    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)    at org.springframework.boot.SpringApplication.run(SpringApplication.java:316)    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260)    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248)    at com.jimmy.Application.main(Application.java:25)Caused by: org.springframework.context.ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean.    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.getWebServerFactory(ServletWebServerApplicationContext.java:206)    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.createWebServer(ServletWebServerApplicationContext.java:180)    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:154)    ... 8 more

呈现该谬误的起因是上述步骤2,移除了内置的tomcat,而放在tomcat中的war包能失常运行,是因为tomcat中已自带了这个相干的包。

如果想持续在IDE中应用启动类启动我的项目,只须要将步骤2移除内置tomcat的步骤正文即可。