Spring Boot项目部署到外部Tomcat服务器

前言

Spring Boot项目一般都是内嵌tomcat或者jetty服务器运行,很少用war包部署到外部的服务容器,即使放到linux中,一般也是直接启动Application类,但是有些时候我们需要部署到外部的服务器,这对于Spring Boot来说却有点麻烦

部署步骤

一、 修改pom

  1. 首先把package改为war
<packaging>warpackaging>
  1. 由于spring-boot-starter-web中内置了tomcat,所以要把它移除
<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-thymeleafartifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-tomcatartifactId>
        exclusion>
    exclusions>
dependency>

但是为了测试,最好这样引用:

<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-tomcatartifactId>
    
    <scope>providedscope>
dependency>

二、提供一个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);
    }
}

如果这里报异常,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>
        
        <plugin>
            <groupId>org.apache.maven.pluginsgroupId>
            <artifactId>maven-war-pluginartifactId>
            <configuration>
                <warName>easydeploywarName>
            configuration>
        plugin>
    plugins>
build>

假如项目的controller路径为index,则此时的访问路径为:
localhost:8080/easydeploy/index

你可能感兴趣的:(SpringBoot)