首先看下项目结构,在resources/properties路径下建三个不同的properties文件。
命名上可以区分一下
然后在pom文件中加入如下配置
最外侧project标签内加入,其中test,pre,prd就是后面打包时候的参数标志,表示用哪个配置文件
<profiles>
<profile>
<id>test</id>
<properties>
<autoconfig.properties>antx_test.properties</autoconfig.properties>
</properties>
</profile>
<profile>
<id>pre</id>
<properties>
<autoconfig.properties>antx_pre.properties</autoconfig.properties>
</properties>
</profile>
<profile>
<id>prd</id>
<properties>
<autoconfig.properties>antx_prd.properties</autoconfig.properties>
</properties>
</profile>
</profiles>
然后在plugin中加入如下配置
<plugin>
<groupId>com.alibaba.citrus.tool</groupId>
<artifactId>autoconfig-maven-plugin</artifactId>
<version>1.2</version>
<configuration>
<userProperties>src/main/resources/properties/${autoconfig.properties}</userProperties>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>autoconfig</goal>
</goals>
</execution>
</executions>
</plugin>
最后打包的时候加入-P 参数,表示采用哪个配置文件
mvn package -P test
20180814更新
以上是通过maven的方式进行多环境配置,如果是springboot的工程,可以不用那么复杂
在resource路径下新建不同的配置文件,文件名命名规则为:application-{profile}.properties,{profile}对应你的环境标识。如:
application-dev.properties:开发环境
application-test.properties:测试环境
然后在启动命令里标明使用哪份配置文件,如果启动命令里没有指明参数,默认加载application.properties。
java -jar xxx.jar --spring.profiles.active=test
开发过程中,出现过不生效的情况,不知道具体原因,然后可以在应用启动入口application上加上注解
@PropertySource("application-${spring.profiles.active}.properties")