今天在项目中配置了sql-maven-plugin插件已进行自动化数据库部署,由于项目中已经在一个.properties配置文件中配置了不同环境下的数据库连接参数,自然不想再在pom.xml中再配置一份,所以打算让pom.xml从.properties文件中读取数据库的配置信息。在网上找到了properties-maven-plugin插件,可以读取.properties文件,按照官方示例,配置如下:
<!-- 读取配置文件属性 -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>properties-maven-plugin</artifactId>
<version>1.0-alpha-2</version>
<executions>
<execution>
<phase>process-resources</phase>
<goals>
<goal>read-project-properties</goal>
</goals>
<configuration>
<files>
<file>${basedir}/config.properties</file>
</files>
</configuration>
</execution>
</executions>
</plugin>
运行mvn properties:read-project-properties,输出报错:
[ERROR] Failed to execute goal org.codehaus.mojo:properties-maven-plugin:1.0-alpha-2:read-project-properties (default-cli) on project applyccard2: The parameters 'files' for goal org.codehaus.mojo:properties-maven-plugin:1.0-alpha-2:read-project-properties are missing or invalid -> [Help 1]
打开DEBUG选项,再运行,发现插件根本没有找到我配置的<configuration>节点:
[DEBUG] -----------------------------------------------------------------------
[DEBUG] Goal: org.codehaus.mojo:properties-maven-plugin:1.0-alpha-2:read-project-properties (default-cli)
[DEBUG] Style: Regular
[DEBUG] Configuration: <?xml version="1.0" encoding="UTF-8"?>
<configuration>
<project default-value="${project}"/>
<quiet default-value="false"/>
</configuration>
[DEBUG] =======================================================================
经过无数次google,终于在stackoverflow找了一个帖子(properties-maven-plugin: Error loading properties-file),他的办法就是把<configuration>节点移出<executions>节点。于是,我把properties-maven-plugin插件的配置修改成这样:
<!-- 读取配置文件属性 -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>properties-maven-plugin</artifactId>
<version>1.0-alpha-2</version>
<configuration>
<files>
<file>${basedir}/config.properties</file>
</files>
</configuration>
<executions>
<execution>
<phase>process-resources</phase>
<goals>
<goal>read-project-properties</goal>
</goals>
</execution>
</executions>
</plugin>
再运行mvn properties:read-project-properties,终于成功读取到.properyties文件!
[DEBUG] Loading property file: D:\workspaceEclipse\applyccard2\config.properties
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.407s
[INFO] Finished at: Thu Sep 20 12:42:12 CST 2012
[INFO] Final Memory: 3M/15M
[INFO] ------------------------------------------------------------------------
But, WHY?!WHY?!WHY?!
查阅maven官网,找到一篇讲解插件配置的文章《Guide to Configuring Plug-ins》终于解惑:
You can also configure a mojo using the <executions> tag. This is most commonly used for mojos that are intended to participate in some phases of the build lifecycle.
把<configuration>再挪到<execution>中,执行 mvn compile, 成功读取config.properties文件。