说明
如果每次运行都需要加-Dspring.profiles.active={profile}
未免太过麻烦,这里干脆直接用maven profile的方式,省时省力解决这个问题。
前置工作
pom.xml中编写自己的profile
<profiles>
<profile>
<id>default</id>
<activation>
<!--默认启用-->
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<spring.active.profile>default</spring.active.profile>
</properties>
</profile>
<profile>
<id>dev</id>
<properties>
<spring.active.profile>dev</spring.active.profile>
</properties>
</profile>
</profiles>
在application.properties中可以加入这么一段spring.profiles.active=@spring.active.profile@
,这里的@xxx@对应您定义的profile中的properties中的要使用的标签名,@
这个东西是spring-boot-parent中定义的:
<properties>
<resource.delimiter>@</resource.delimiter>
</properties>
接着我们编写build的选项
<build>
<!--重命名打包-->
<finalName>${artifactId}-${spring.active.profile}</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!-- 用于处理resources下面的一些替换符-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
</plugin>
</plugins>
<resources>
<!--排除配置文件-->
<resource>
<directory>src/main/resources</directory>
<!--先排除所有的配置文件-->
<excludes>
<!--使用通配符,当然可以定义多个exclude标签进行排除-->
<exclude>application-*.properties</exclude>
</excludes>
</resource>
<!--根据激活条件引入打包所需的配置和文件-->
<resource>
<directory>src/main/resources</directory>
<!--引入所需环境的配置文件-->
<filtering>true</filtering>
<includes>
<!--原本的配置文件-->
<include>application.properties</include>
<!--根据maven选择环境导入配置文件-->
<include>application-${spring.active.profile}.properties</include>
</includes>
</resource>
</resources>
</build>
使用
编写properties
选择配置文件或者使用maven的参数-P {profile}
,选择完成之后最好先clean再去构建
构建之后效果如下
参考:
嗯,挺全乎儿的,Spring Boot 多环境配置都在这里了,你喜欢哪种?
最痛的领悟---maven的filtering,includes,excludes标签用法