1. 将全局配置文件拷贝多份,按照不同的环境命名
将全局配置文件,按照“开发”,“测试”,“生产”环境,分别将全局配置文件命名为
application-dev.properties
application-test.properties
application-pro.properties
我这边用 conf 作为前缀, 然后把全局配置文件放在项目的根目录中
2.在根项目的pom文件中配置maven启动时的环境profile
<profiles>
<!--默认激活开发配置,使用index-dev.properties来替换实际的文件key -->
<profile>
<id>dev</id>
<properties>
<deploy.env>dev</deploy.env>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<!-- 测试环境配置 -->
<profile>
<id>test</id>
<properties>
<deploy.env>test</deploy.env>
</properties>
</profile>
<!-- 生产环境配置 -->
<profile>
<id>pro</id>
<properties>
<deploy.env>pro</deploy.env>
</properties>
</profile>
</profiles>
3.在子模块的pom文件中定义filter
在资源过滤被激活的时候,Maven会扫描filter指定profile对应的配置文件资源,寻找由${}包围的Maven属性的引用。一旦它找到这些引用,它就会使用合适的值去替换它们.
在子模块的pom.xml文件加入: filter中是我们的全局配置文件的相对地址
<filters>
<filter>../conf/conf-${deploy.env}.properties</filter>
</filters>
由于我们在profile中定义的dev为默认,这样的话 , 这个模块中的配置文件,${}中的参数都会去conf-dev.properties
中查找替换
比如我配置的redis , 在模块的配置文件中:
conf-dev.properties
中redis的配置