问题
开发一个项目,主要有开发、测试和最终部署上线几个阶段,每个阶段对配置(数据库、日志)都有不同的设置。每次上线都由部署工程师负责修改配置并上线。这样的工作方式导致每次上线时大家都心惊胆颤,决定研究下maven如何解决这个问题。
思路
将几个环境的配置项分类,概括为数据库配置、log日志路径配置、外部依赖的接口配置。
如果能实现在生成不同的发布包时对资源进行不同的替换就可以达到目的了。而maven的build结合profile,即可动态指定配置文件来实现。
步骤
1、首先需要在pom文件中确定filter和要filter的资源,这是通过在build节点中添加filter和resource来实现的。
2、然后pom文件配置profile的多个id,通过mvn package -P,动态指定配置。
示例
build标签:
<build>
<filters>
<filter>src/main/filters/filter-${env}.properties</filter>
</filters>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
build/resource/directory配置表示要对src/main/resources下的资源进行过滤;build/resource/filtering配置表示过滤方式采用文件过滤。
build/filter表示过滤文件为src/main/filters/filter-${env}.properties,其中${env}是一个变量,通过在pom文件中通过profile定义。
profiles标签:
<!--此处可以配置默认激活-->
<properties>
<env>dev</env>
</properties>
<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>product</id>
<properties>
<env>product</env>
</properties>
</profile>
</profiles>
properties/env配置${env}的默认值。
profiles配置不同环境的配置。profile/id配置id,profile/properties/env配置${env}。
通过mvn package -P(id),动态指定配置${env}。例如:maven package -Pproduct,则会使用 filter-product.properties中的内容来替换resources目录中的配置文件,比如我们项目resources下有db.properties。
db.properties文件内容如下:
...
jdbc.connection.url=${ymqx.jdbc.url}
jdbc.connection.username=${ymqx.jdbc.username}
jdbc.connection.password=${ymqx.jdbc.password}
...
filter-product.properties文件内容如下:
...
ymqx.jdbc.url=jdbc:mysql://localhost:3306/ymqx?characterEncoding=UTF-8
ymqx.jdbc.username=root
ymqx.jdbc.password=admin
...
maven执行命令 maven package -Pproduct 后,db.properties的内容:
...
jdbc.connection.url=jdbc:mysql://localhost:3306/ymqx?characterEncoding=UTF-8
jdbc.connection.username=root
jdbc.connection.password=admin
...
小结
build结合profile实现多环境动态配置完成。build指定资源文件目录;profile配置多环境的配置id;通过maven package -P,指定id动态加载资源文件。