1. 将打包方式修改为war
<packaging>war</packaging>
2. 移除tomcat依赖或者将tomcat依赖scope改为provide
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<!--移除tomcat依赖-->
<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>
3. 继承org.springframework.boot.web.servlet.support.SpringBootServletInitializer,实现configure方法
为什么继承该类,SpringBootServletInitializer源码注释:
Note that a WebApplicationInitializer is only needed if you are building a war file and deploying it. If you prefer to run an embedded web server then you won’t need this at all.
注意,如果您正在构建WAR文件并部署它,则需要WebApplicationInitializer。如果你喜欢运行一个嵌入式Web服务器,那么你根本不需要这个。
启动类代码:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
1.方式一,启动类继承SpringBootServletInitializer实现configure:
@SpringBootApplication
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(Application.class);
}
}
2.方式二,新增加一个类继承SpringBootServletInitializer实现configure:
public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
//此处的Application.class为带有@SpringBootApplication注解的启动类
return builder.sources(Application.class);
}
}
使用外部Tomcat部署访问的时候,application.properties(或者application.yml)中配置的
server.port=
server.servlet.context-path=
将失效,请使用tomcat的端口,tomcat,webapps下项目名进行访问。为了防止应用上下文所导致的项目访问资源加载不到的问题,建议pom.xml文件中标签下添加标签:
<build>
<!-- 应与application.properties(或application.yml)中context-path保持一致 -->
<finalName>war包名称</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
4.使用idea生成war包
在idea菜单栏中找到Build---->build Arufacts生成war,生成的war包会在target文件夹中找到