前言
公司的项目目前在有序的开发中,由于懒惰以及对Maven不是很熟悉,多环境的配置一直没有处理。每次提交代码,都需要检查一下,避免提交了本地的配置文件上去。长期如此,不是办法,于是今天费点时间,研究了下maven的多环境支持配置。
问题
目前存在2个环境。一个是本地开发环境。一个是内部服务器的测试环境。由于还未开发完毕,暂时没有生产环境。
目前使用的配置是
jdbc.properties
jdbc.type=mysql
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/lightai?useUnicode=true&characterEncoding=UTF8&useSSL=false&tinyInt1isBit=false
jdbc.username=root
jdbc.password=123456
# Configuration needs to be studied
c3p0.acquireIncrement=3
c3p0.initialPoolSize=3
c3p0.idleConnectionTestPeriod=60
c3p0.minPoolSize=2
c3p0.maxPoolSize=50
c3p0.maxStatements=100
c3p0.numHelperThreads=10
c3p0.maxIdleTime=600
c3p0.testConnectionOnCheckout=true
c3p0.preferredTestQuery=select 1 from net_logs
对比环境的差异,目前只有一个不同。就是数据库的密码不同。
因此只需要实现密码的多环境替换即可。
jdbc.password=123456
解决
maven要解决多环境的问题。需要下面的配置。
- profile
配置了3个环境。其中默认的是本地开发环境。
<profiles>
<profile>
<!-- 本地开发环境 -->
<id>dev</id>
<properties>
<profiles.active>dev</profiles.active>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<!-- 测试环境 -->
<id>test</id>
<properties>
<profiles.active>test</profiles.active>
</properties>
</profile>
<profile>
<!-- 生产环境 -->
<id>pro</id>
<properties>
<profiles.active>pro</profiles.active>
</properties>
</profile>
</profiles>
- filters
创建环境对应的配置。
![](https://img.haomeiwen.com/i32778/29a7233bb49dcf57.png)
这里就配置一个密码即可。
jdbc.password=123456
载入上面的配置资源路径。其中${profiles.active} 是变量,会判断当前的环境。默认是dev
<filters>
<filter>src/main/filters/filter-${profiles.active}.properties</filter>
</filters>
开启过滤。开启后,前面的环境专属配置加载才会有效。
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
在需要配置密码的地方,按如下设置,则密码会在不同的环境下,加载指定的值。
jdbc.password=${jdbc.password}
最后执行打包命令
开发环境
mvn clean package -Pdev
测试环境
mvn clean package -Ptest
生产环境
mvn clean package -Ppro
此事已经ok了。
补充
我本地使用的idea工具。
![](https://img.haomeiwen.com/i32778/25e87b98849a4e84.png)
测试环境是 通过 jenkis自动部署。
![](https://img.haomeiwen.com/i32778/3181de543ddca8ee.png)
网友评论