【转】把spring-boot项目部署到tomcat容器中

本文共有3468个字,页面加载耗时0.001秒,关键词:

把spring-boot项目按照平常的web项目一样发布到tomcat容器下

一、修改打包形式

pom.xml 里设置

<packaging>war</packaging>

二、移除嵌入式tomcat插件

pom.xml 里找到 spring-boot-starter-web 依赖节点,在其中添加如下代码,

<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>

三、添加 servlet-api 的依赖

下面两种方式都可以,任选其一

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>org.apache.tomcat</groupId>
    <artifactId>tomcat-servlet-api</artifactId>
    <version>8.0.36</version>
    <scope>provided</scope>
</dependency>

四、修改启动类,并重写初始化方法

SpringBootStartApplication 启动类,其代码如下:

/**
 * 修改启动类,继承 SpringBootServletInitializer 并重写 configure 方法
 */
@SpringBootApplication
@EnableTransactionManagement
public class SpringBootStartApplication extends SpringBootServletInitializer {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootStartApplication.class, args);
    }


    // 用于构建war文件并进行部署
    @Override
    protected SpringApplicationBuilder configure(
            SpringApplicationBuilder builder) {
        return builder.sources(this.getClass());
    }
}

五、打包部署

打包部署

等待打包完成,出现 [INFO] BUILD SUCCESS 即为打包成功。
BUILD SUCCESS

然后把target目录下的war包放到tomcat的webapps目录下

target目录下的war包

启动tomcat,即可自动解压部署。
最后在浏览器中输入

http://localhost:[端口号]/[打包项目名]/

发布成功

如果遇到错误

1.Maven打包出错Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.22.2:test

在使用maven打包时,出现以下错误

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.22.2:test (default-test) on project flow-traffic-statistics: Unable to generate classpath: org.apache.maven.artifact.resolver.ArtifactResolutionException: Unable to get dependency information for org.apache.maven.surefire:surefire-junit-platform:jar:2.22.2: Failed to retrieve POM for org.apache.maven.surefire:surefire-junit-platform:jar:2.22.2: Could not transfer artifact org.apache.maven.surefire:surefire-junit-platform:pom:2.22.2 from/to central (https://repo.maven.apache.org/maven2): Remote host closed connection during handshake

解决方法:
在pom.xml中build节点添加以下内容

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <configuration>
        <skipTests>true</skipTests>
    </configuration>
</plugin>

修复失败1

参考链接

https://blog.csdn.net/ksksjipeng/article/details/105589297
https://blog.csdn.net/qq_34802416/article/details/86485522
https://blog.csdn.net/javahighness/article/details/52515226

扫码在手机查看