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 failed
org.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 的步骤正文即可。