背景
最近在使用webx 的 autonconfig工具进行多环境间配置文件的变量替换。
常常我们遇到不同环境打包问题都是自己搞一套脚步来做,但是如何成体系的解决这一问题?
autoconfig工具主要有两个用法:
- 不同环境环境的打包要使用不同的配置(如DB连接,版本信息等),这时候可以把需要替换的配置定义为占位符,使用maven的profile和maven的autoconfig插件来指定不同的properties文件,打包的时候,autoconfig就回去对应的properties文件中取对应占位符的值,替换占位符。(正式本项目的需求)
- 用于共享富客户端。在项目组协同工作的时候,往往别人用到自己项目的功能,我们都会共享一个jar包给对方。这是,如果jar包中有需要被替换的配置文件,不可能每一个使用者我们都给一个定制版。那么我们将变量定义为占位符,使用者拿到包后,autoconfig会自动将其中的占位符替换成properties里的值(需要我们自己填入)
这上面两个用法可以结合使用,这样就非常强大。
使用方法
- 在pom.xml中加入autoconfig插件
<build>
<finalName>edas-vendor</finalName>
<plugins>
<plugin>
<groupId>com.alibaba.citrus.tool</groupId>
<artifactId>autoconfig-maven-plugin</artifactId>
<version>1.2</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>autoconfig</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
- 定义不同环境的properties
<profiles>
<profile>
<id>daily</id>
<properties>
<autoconfig.userProperties>${user.home}/antx-daily.properties</autoconfig.userProperties>
</properties>
</profile>
<profile>
<id>online</id>
<properties>
<autoconfig.userProperties>${user.home}/antx-online.properties</autoconfig.userProperties>
</properties>
</profile>
</profiles>
这里定义了两套环境,一套daily一套online。分别对应home目录下面的
antx-daily.properties
和
antx-online.properties
配置文件。
- 定义
目录结构如下:auton-config.xml
Webx autoconfig 多环境打包 使用总结
内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<config>
<group>
<property name="config.xxxx" description="配置项描述"/>
</group>
<script>
<generate template="template.vm" destfile="WEB-INF/classes/template.xml" charset="UTF-8"/>
</script>
</config>
定义了一个config.xxxx的占位符
定义了一个template.vm的配置文件模板,替换后的模板将会保存为WEB-INF/classes/template.xml
注意:autonconfig寻找模板文件的规则:
1. 在auto-config.xml相同目录下找
2. war包根目录下找
template.vm模板内容:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:hsf="http://www.taobao.com/hsf"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.taobao.com/hsf
http://www.taobao.com/hsf/hsf.xsd"
default-autowire="byName">
<hsf:consumer id="xxxx" interface="com.xxx.xxxx" version="${config.xxxx}"/>
</beans>
- 在home目录下创建
和antx-daily.properties
antx-online.properties
antx-daily.properties内容:
config.xxxx = daily
antx-online.properties内容:
config.xxxx = online
- 执行maven打包
如果想使用online的配置,执行:
mvn clean package -P online
这样就会将
template.vm
中的
config.xxxx
替换成online
如果想使用daily的配置,执行:
mvn clean package -P daily
这样就会将
template.vm
中的config.xxxx替换成daily
如果是IDEA,可以直接勾选profile,然后选择maven命令执行。