1. Yml multi-environment configuration
In Spring Boot
the multi-environment configuration file name, application-{profile}.yml
the format needs to be met, which {profile}
corresponds to your environment identifier;
application-dev 开发环境 application-test 测试环境 application-prod 生产环境
If we want to activate a certain environment, we only need to application.yml
:
spring:
profiles:
active: dev
Additionally, assume we configure some basic settings like:
application-dev.yml
server:
port: 9001
application-test.yml
server:
port: 9002
application-prod.yml
server:
port: 9003
At this point, when we go to modify application.yml
:
- Change to
dev
- Change to
test
- Change to
prod
2. Create multi-environment profile packaging
Through the above steps, you can easily switch the current environment, but it is a little troublesome. Is there any configuration file that can be used 代替手动更改profile并且能创建多环境profile打包呢
?
答案是肯定的
pom.xml
Add a profile node to the pom file, and add packaging and filtering configuration file rules to the resources node under build.
<profiles>
<profile>
<!-- 开发环境 -->
<id>dev</id>
<properties>
<profileActive>dev</profileActive>
</properties>
<!-- 默认激活的环境 -->
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<!-- 测试环境 -->
<id>test</id>
<properties>
<profileActive>test</profileActive>
</properties>
</profile>
<profile>
<!-- 生产环境 -->
<id>prod</id>
<properties>
<profileActive>prod</profileActive>
</properties>
</profile>
</profiles>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>application-${profileActive}.yml</include>
<include>application.yml</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
application.yml
Configure a dynamic attribute in as a placeholder. The default separator is @property name@. This attribute will be replaced by the parameters passed in when maven is packaged ;
spring:
profiles:
active: @profileActive@
The visual selection environment on the right makes work more efficient;
maven multi-environment packaging
The packaging and filtering configuration file rules also use a placeholder, which will also be replaced by parameters passed in through maven when packaging.
- 1.
通过 -D命令传入属性值profileActive
, such as:
clean install -Dmaven.test.skip=true -DprofileActive=dev
- 2.
通过-P命令指定profile环境
, such as:
clean package -P prod
The visual selection on the right is more convenient: