Spring Boot项目部署到外部Tomcat服务器
前言
Spring Boot项目一般都是内嵌tomcat或者jetty服务器运行,很少用war包部署到外部的服务容器,即使放到linux中,一般也是直接启动Application类,但是有些时候我们需要部署到外部的服务器,这对于Spring Boot来说却有点麻烦
部署步骤
一、 修改pom
- 首先把package改为war
<packaging>war</packaging>
- 1
- 由于spring-boot-starter-web中内置了tomcat,所以要把它移除
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
但是为了测试,最好这样引用:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<!-- 要为provided-->
<scope>provided</scope>
</dependency>
- 1
- 2
- 3
- 4
- 5
- 6
二、提供一个SpringBootServletInitializer子类,并重写configure方法
@SpringBootApplication
public class EasyDeployWarApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(EasyDeployWarApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(EasyDeployWarApplication.class, args);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
如果这里报异常,Caused by: java.lang.IllegalStateException: No SpringApplication sources have been defined. Either override the configure method or add an @Configuration annotation,这是由于项目中有两个Application启动类导致的,删除原来那个即可
三、可以通过war插件来指定war包的名字
<build>
<plugins>
<!-- war部署使用-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<warName>easydeploy</warName>
</configuration>
</plugin>
</plugins>
</build>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
假如项目的controller路径为index,则此时的访问路径为:
localhost:8080/easydeploy/index