在许多情况下我们需要动态地读取配置信息,以构建特定的应用系统。一般地,我们会考虑采用ant脚本帮我们做到这一点。但是,ant脚本所特定的语法结构不是Java程序员所熟悉的。本文提供另外一种思路--通过GMaven plugin调用Groovy脚本帮我们读取配置文件,替换配置文件中的变量和拷贝到特定的位置。
1. 在POM文件中添加GMaven plugin
<build>
<plugins>
<plugin>
<groupId>org.codehaus.gmaven</groupId>
<artifactId>gmaven-plugin</artifactId>
<executions>
<execution>
<phase>install</phase>
<goals>
<goal>execute</goal>
</goals>
<configuration>
<source>${pom.basedir}/build.groovy</source>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
2. 在pom.xml文件所在的目录中添加groovy脚本build.groovy (以下脚本的作用是根据master-system-config.properties的属性修改本项目XXX-system-config.properties的属性)。需要注意的是GMaven plugin提供一些变量,让我们在groovy脚本中可以取得pom文件的属性和变量,比如project,settings等等,具体请看这里http://docs.codehaus.org/display/GMAVEN/Executing+Groovy+Code#ExecutingGroovyCode-CustomProperties
if (project.packaging == 'war'){
println 'build war...'
def projectName = project.name
def projectBaseDir = project.basedir;
def masterProps = new Properties()
def masterConfigFile = new File("master-system-config.properties")
if (masterConfigFile.exists()) {
masterConfigFile.withInputStream{
stream -> masterProps.load(stream)
}
def systemProps = new Properties()
new File("${projectBaseDir}\\web\\src\\${projectName}-system-config.properties").withInputStream{
stream -> systemProps.load(stream)
}
for (name in masterProps.propertyNames()){
systemProps.put(name, masterProps.getProperty(name))
}
new File("${projectBaseDir}\\web\\src\\${projectName}-system-config.properties").withOutputStream{
os -> systemProps.store(os, "updated")
}
}
}