autoPackageDemo,自动识别打包环境
Spring Boot版本:2.3.4.RELEASE
Maven项目
场景
当我们打包项目需要切换环境的时候,通常是在application.yml中修改指定环境:
spring:
profiles:
# active: dev # 开发环境
active: pro # 生产环境
复制代码
目的
我们希望能避免频繁的修改配置文件,改成在打包指令中添加指定环境的方式,像这样:
spring:
profiles:
active: @activatedProperties@ # 自动识别环境
复制代码
打包指令:
mvn clean package -Dmaven.test.skip=true -P pro
实现
只需要修改pom.xml就可以了
pom.xml
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.cc</groupId>
<artifactId>autoPackageDemo</artifactId>
<version>1.0.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.4.RELEASE</version>
</parent>
<dependencies>
<!--springboot启动器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<profiles>
<profile>
<id>dev</id>
<properties>
<activatedProperties>dev</activatedProperties>
</properties>
<activation>
<!--默认情况下使用dev开发配置-->
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<!--指定可以用来打包的配置文件1-->
<profile>
<id>pro</id>
<properties>
<activatedProperties>pro</activatedProperties>
</properties>
</profile>
<!--有其他环境的话就继续添加-->
<!--...-->
</profiles>
<build>
<!--指定打包的配置文件2-->
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<!--指定包名-->
<finalName>app</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
复制代码
配置文件:
application.yml:
server:
port: 8888
spring:
profiles:
active: @activatedProperties@ # 自动识别环境
复制代码
application-dev.yml:
myvalue: dev
复制代码
application-pro.yml:
myvalue: pro
复制代码
测试
新建接口来测试下:
package com.cc.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@Value("${myvalue}")
private String myvalue;
@GetMapping("/env")
public String env() {
return "当前的启动环境是:" + myvalue;
}
}
复制代码
结果:
-
在编译器中启动的时候默认是dev环境,请求结果是:
- 当前的启动环境是:dev
-
指定pro环境打包的jar包,请求结果是:
- 当前的启动环境是:pro
注:打包后,如果编译器运行紊乱,尝试执行maven clean以及maven install清理旧缓存。