一、配置三步操作
1. 修改项目的打包类型
<packaging>war</packaging>
2. 去掉内嵌 tomcat 依赖(非必须)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<!-- scope设置为provided, 表明依赖由外部容器提供,在打包时会将该包排除 -->
<scope>provided</scope>
</dependency>
打包后的war包解压后,scope 为 provided 的依赖 (这里为内嵌tomcat)放在lib-provided目录下,而不是lib目录
3. 继承SpringBootServletInitializer,重写configure方法
3.1. 方式一
@RestController
@SpringBootApplication
public class TomcatDemoApplication extends SpringBootServletInitializer{
public static void main(String[] args) {
SpringApplication.run(TomcatDemoApplication.class, args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(TomcatDemoApplication.class);
}
@GetMapping("/hello")
public String hello() {
return "hello world";
}
}
3.2. 方式二
@RestController
@SpringBootApplication
public class TomcatDemoApplication extends SpringBootServletInitializer{
public static void main(String[] args) {
SpringApplication.run(TomcatDemoApplication.class, args);
}
@GetMapping("/hello")
public String hello() {
return "hello world";
}
}
public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(TomcatDemoApplication.class);
}
}
二、打包部署步骤
1. mvn package打包,打包后包名默认为:
<artifactId>-<version>.<packaging>
针对以下项目配置:
<groupId>com.example</groupId>
<artifactId>tomcat-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
打包后包名即为:tomcat-demo-0.0.1-SNAPSHOT.war
2. 把打好的war包放到外部 tomcat 的webapp目录下,启动 bin/start.bat 即可
3. 访问 http://localhost:8085/tomcat-demo-0.0.1-SNAPSHOT/hello,页面正常返回 “hello world”
三、注意事项
1. 用外部 tomcat 部署项目后,Spring Boot 内部的一些配置无效,例如:
server.port, server.servlet.context-path 等, 因为这些配置都是针对内嵌tomcat容器的,要修改端口号和部署根路径的话,需要修改外部tomcat的相关配置
2. 更该打包后的默认包名
<build>
<finalName>tomcat-demo</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
这样打包后包名为
<finalName>.war, 这里即为tomcat-demo.war