您的位置:首页 > 其它

maven 生产环境、开发环境替换配置文件打包

2017-06-17 22:29 716 查看

需求

一个很常见的需求,在开发和生产环境打包时的配置文件不同,比如数据库连接地址,都在project-config.properties文件中,在测试环境中jdbc.url=localhost:3306/xx,而在正式环境中就是jdbc.url=19.80.90.10/xx,类似这样。

资源过滤

maven提供了资源过滤功能,来替换文件中的变量,基于此,我们能实现配置替换。基本思路是分别创建配置文件,比如dev/project-configure.properties和pro/project-configure.properties,在编译时用这两个文件中的值,替换src/main/resources底下的project-configure.properties。

具体过程

在工程根目录创建filters文件夹,在其中,分别创建project-config.properties文件,顾名思义,dev下边放的是开发环境配置,pro(duction)是生产环境配置,

dev中的project-config.properties

jdbc.url=localhost:3306/xx


pro中的project-config.properties

jdbc.url=19.80.90.10/xx


src/main/resources下的project-config.properties

jdbc.url=${jdbc.url}


在项目的pom.xml中配置

这里配置了两个profile,dev和pro,过滤器文件分别使用对应的project-config.properties,并且dev是默认启用。

<profiles>
<profile>
<!-- 本地开发环境 -->
<id>dev</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<build>
<filters>
<filter>${basedir}/filters/dev/project-config.properties</filter>
</filters>
</build>
</profile>

<profile>
<!-- 生产环境 -->
<id>pro</id>
<build>
<filters>
<filter>${basedir}/filters/pro/project-config.properties</filter>
</filters>
</build>
</profile>
</profiles>


另外build中的resource需要将properties的过滤改为true

<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>

</build>


这样maven在编译时,用 filters/dev(pro)/project-configure.properties中的键值对,替换src/main/resources下所有的properties文件进行进行过滤替换。

总体效果图





疑问

当时配置后,有个疑问,平常开发时,比如摁ctrl+F9编译,也能自动替换配置吗?试验后得知,是的。因为在编译时也执行了maven编译命令,执行maven,肯定用到pom.xml所以profile生效替换了配置。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  maven