Spring Boot 2 打War 包部署

Spring Boot War 部署

1 修改打包方式为 War

修改 Spring Boot 项目的 pom.xml 文件将打包方式修改为 war 。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>big</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>big</name>
    <description>Demo project for Spring Boot</description>
    <packaging>war</packaging>

2 排除内嵌的Web容器。

1.Spring Boot 内嵌的Tomcat默认已经集成在spring-boot-starter-web包里,排除掉它。但是这种方式Servlet Api依赖也排除掉了,   SpringBootServletInitializer 需要依赖 Servlet Api , 因此要加上它。version要跟外置的Tomcat 版本兼容


<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>${version}</version>
    <scope>provided</scope>
</dependency>

2.我们通过引入 spring-boot-starter-tomcat 覆盖掉默认的内置 Tomcat 并设置scopeprovided

<!--打包的时候可以不用包进去,别的设施会提供。事实上该依赖理论上可以参与编译,测试,运行等周期。
                相当于compile,但是打包阶段做了exclude操作-->
 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-tomcat</artifactId>
     <scope>provided</scope>
 </dependency>

3 实现 SpringBootServletInitializer 接口

新建 SpringBootServletInitializer 的实现类 ServletInitializer 如下:

 package com.example.big;

 import org.springframework.boot.builder.SpringApplicationBuilder;
 import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;


 public class ServletInitializer extends SpringBootServletInitializer {

     @Override
     protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {

         return application.sources(BigSpringBootApplication.class);
     }

 }

其中 BigSpringBootApplication 是 Spring Boot 的入口类:

 package com.example.big;

 import org.springframework.boot.SpringApplication;
 import org.springframework.boot.autoconfigure.SpringBootApplication;


 @SpringBootApplication
 public class BigSpringBootApplication {

     public static void main(String[] args) {
         SpringApplication.run(BigSpringBootApplication.class, args);
     }

 }

4 执行编译打包命令

mvn clean package -Dmaven.test.skip=true

发布了82 篇原创文章 · 获赞 7 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/a972669015/article/details/102956371