配置SpringBoot方便的切换jar和war

配置SpringBoot方便的切换jar和war

网上关于如何切换,其实说的很明确,本文主要通过profile进行快速切换已实现在不同场合下,用不同的打包方式。

jar到war修改步骤

  • pom文件修改

    1. packaging配置由jar改为war
    2. 排除tomcat等容器的依赖
    3. 配置web.xml或者无web.xml打包处理
  • 入口类修改

    1. 添加ServletInitializer

特别注意:当改成war包的时候,application.properties配置的server.portserver.servlet.context-path就无效了,遵从war容器的安排。

配置pom

配置packaging

```<packaging>${pom.package}</packaging> ```

修改build


&lt;!-- 作用是打war包的时候,不带版本号 --&gt;
&lt;finalName&gt;${pom.packageName}&lt;/finalName&gt;

&lt;!--加入plugin--&gt;
&lt;plugin&gt;
  &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
  &lt;artifactId&gt;maven-war-plugin&lt;/artifactId&gt;
  &lt;version&gt;3.2.2&lt;/version&gt;
  &lt;configuration&gt;
    &lt;!--如果想在没有web.xml文件的情况下构建WAR,请设置为false。--&gt;
    &lt;failOnMissingWebXml&gt;false&lt;/failOnMissingWebXml&gt;
  &lt;/configuration&gt;
&lt;/plugin&gt;

排除容器

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

配置profile

```<profiles> <profile> <!-- 开发环境 --> <id>jar</id> <activation> <activeByDefault>true</activeByDefault> </activation> <properties> <pom.package>jar</pom.package> <pom.packageName>${project.artifactId}-${project.version}</pom.packageName> <pom.profiles.active>dev</pom.profiles.active> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </dependency> </dependencies> </profile> <profile> <id>war</id> <properties> <pom.package>war</pom.package> <pom.packageName>${project.artifactId}</pom.packageName> <pom.profiles.active>linux</pom.profiles.active> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> </dependencies> </profile> </profiles> ```

修改入口类

  1. 入口类继承SpringBootServletInitializer
  2. 重写configure方法

使用@Profile注解,当启用war配置的时候,初始化Servlet。


public class Application extends SpringBootServletInitializer {

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

  @Profile(value = {"war"})
  @Override
  protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
    return application.sources(Application.class);
  }
}

来源:https://segmentfault.com/a/1190000017926997

原文地址:https://www.cnblogs.com/lalalagq/p/10286953.html