maven的properties filter功能可以帮你自动替换配置文件中以${}包裹的变量。
1. spring bean的配置文件app.xml内容:
<!--[if !supportLists]-->1. <!--[endif]-->...
<!--[if !supportLists]-->2. <!--[endif]--> <bean id="dataSource" destroy-method="close"
<!--[if !supportLists]-->3. <!--[endif]--> class="org.apache.commons.dbcp.BasicDataSource">
<!--[if !supportLists]-->4. <!--[endif]--> <property name="driverClassName" value="${jdbc.driverClassName}"/>
<!--[if !supportLists]-->5. <!--[endif]--> <property name="url" value="${jdbc.url}"/>
<!--[if !supportLists]-->6. <!--[endif]--> <property name="username" value="${jdbc.username}"/>
<!--[if !supportLists]-->7. <!--[endif]--> <property name="password" value="${jdbc.password}"/>
<!--[if !supportLists]-->8. <!--[endif]--> </bean>
<!--[if !supportLists]-->9. <!--[endif]-->...
该配置文件放置在src/main/resources目录下。
2.pom.xml中的build标记内添加:
<!--[if !supportLists]-->1. <!--[endif]--><resources>
<!--[if !supportLists]-->2. <!--[endif]--> <resource>
<!--[if !supportLists]-->3. <!--[endif]--> <directory>src/main/resources</directory>
<!--[if !supportLists]-->4. <!--[endif]--> <filtering>true</filtering>
<!--[if !supportLists]-->5. <!--[endif]--> </resource>
<!--[if !supportLists]-->6. <!--[endif]--> </resources>
以上xml片段的功能的目的是开启对src/main/resources目录下的property filtering功能。所以上面的配置表示在该目录下的所有文件都会被扫描。如果要指定具体的文件,可以使用includes标记,该标记支持ant路径表达式。
3.在pom.xml中定义属性。
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->
<!--[if !supportLists]-->1. <!--[endif]--><properties>
<!--[if !supportLists]-->2. <!--[endif]--> <jdbc.driverClassName>
<!--[if !supportLists]-->3. <!--[endif]--> com.mysql.jdbc.Driver</jdbc.driverClassName>
<!--[if !supportLists]-->4. <!--[endif]--> <jdbc.url>jdbc:mysql://localhost:3306/development_db</jdbc.url>
<!--[if !supportLists]-->5. <!--[endif]--> <jdbc.username>dev_user</jdbc.username>
<!--[if !supportLists]-->6. <!--[endif]--> <jdbc.password>s3cr3tw0rd</jdbc.password>
<!--[if !supportLists]-->7. <!--[endif]--></properties>
4.编译。
mvn compile
现在查看target/classes目录的app.xml。你会发现xml中的所有变量都被替换了:
<!--[if !supportLists]-->1. <!--[endif]--><bean id="dataSource" destroy-method="close"
<!--[if !supportLists]-->2. <!--[endif]--> class="org.apache.commons.dbcp.BasicDataSource">
<!--[if !supportLists]-->3. <!--[endif]--> <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<!--[if !supportLists]-->4. <!--[endif]--> <property name="url" value="jdbc:mysql://localhost:3306/development_db"/>
<!--[if !supportLists]-->5. <!--[endif]--> <property name="username" value="dev_user"/>
<!--[if !supportLists]-->6. <!--[endif]--> <property name="password" value="s3cr3tw0rd"/></bean>
结合profile功能,你可以在软件发布之前,定义不同的变量。