思路
Maven打包项目是可以通过-P 参数, 使用profile, 向build配置中传递相关的环境配置信息, 例如
- dev (开发)
- test (测试)
- prod (生产)
借鉴
Spring Boot默认提供了很好的多环境配置打包的方案. https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-loading-yaml
和通过配置文件的环境命名获取相应环境的配置
实践
1. 配置pom.xml的profile
如下定义env的三种参数, 设置dev为默认激活(为开发调试方便)
<profiles>
<profile>
<id>dev</id>
<properties>
<env>dev</env>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>test</id>
<properties>
<env>test</env>
</properties>
</profile>
<profile>
<id>prod</id>
<properties>
<env>prod</env>
</properties>
</profile>
</profiles>
pom.xml中就有了变量 ${env}
2. 使用变量 ${env}
在build中使用该变量去引入不同环境的配置文件
<build>
<finalName>xxxxxx</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>config-${env}.properties</include>
<include>config.properties</include>
<include>**.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
使用${env}
引入 src/main/resources
中不同环境的配置文件
3.项目的spring.xml配置设置
所有按照上述的配置后, 在项目spring初始化引入配置文件 需要做如下设置
<context:property-placeholder
file-encoding="utf-8"
ignore-resource-not-found="true"
ignore-unresolvable="false"
location="
classpath:/config.properties,
classpath:/config-dev.properties,
classpath:/config-test.properties,
classpath:/config-prod.properties" />
ignore-resource-not-found
设置为true
因为配置了按环境配置文件打包,项目启动时,只会出现启动两个properties, config.properties
和config-{evn}.properties
, 配置的另外两个文件是查找不到.
ignore-unresolvable
设置为 false
防止出现配置缺失的问题, 及时报错
location
按如下配置路径,加载的顺序为依次的配置文件依次写顺序.
所以先加载默认的 config.properties
, 该文件可以写一些公用,相同的配置参数.
config-${env}.propertis
写一些系统的参数, 比如数据库连接信息.