Spring-boot与maven多环境配置文件设置

时间:2021-03-01 21:50:15

通常在开发时,不同的环境有不同的配置参数,通常会使用maven profile来选择不同环境的配置文件。下面介绍spring-boot项目如何与maven结合,来根据环境选择不通的配置参数。

创建属性配置文件

首先为不同的环境配置不同的属性配置文件,命名需要满足application-{custom_suffix}.properties格式,custom_suffix为自定义后缀,例如生产配置文件起名为application-prod,开发配置文件起名application-dev。其次创建application.properties属性文件。这些文件存放目录为src/main/resources。

application.properties文件用来保存不同环境的公共的配置,及激活最终使用的配置文件。
Spring-boot与maven多环境配置文件设置

修改pom.xml文件

添加下列配置到pom.xml文件中。下列配置定义了dev环境,与prod环境属性配置。properties标签内部定义的属性标签activatedProperties中的值用来替换后文中@activatedProperties@。

<profile>
<id>dev</id>
<properties>
<activatedProperties>dev</activatedProperties>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>release</id>
<properties>
<activatedProperties>release</activatedProperties>
</properties>
</profile>

修改pom.xml build标签

resources部分的作用是,根据maven打包-P参数执行的属性,来对最终属性文件中的参数进行替换。

<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>

</build>

修改application.properties

添加spring.profiles.active=@activatedProperties@ 到application.properties文件中。

最后打包时,@activatedProperties@会根据-P参数被替换为dev或prod,最终application-dev或 application-prod会被作为最终要使用的属性配置文件(根据man -P 参数 确定)。

Spring-boot 1.3后通过@activatedProperties@ 替代${activatedProperties} 来替换属性文件中的参数。

如果有其它属性需要替换,同理修改pom.xml profile中的属性配置即可。

原文地址

http://dolszewski.com/spring/spring-boot-properties-per-maven-profile/