---
title: "profile filters properties  无法替换问题总结"
author: "TimerBin"
date: "2015-10-14T19:09:46Z"
tags: []
categories: ["企业架构"]
slug: "profile-filters-properties"
draft: false
lastmod: "2015-10-14T19:13:21Z"
id: 2249190
url: "https://timerbin.iteye.com/blog/2249190"
---

基于maven pom配置中的profiles配置针对不同环境，使用不同配置文件。

 

第一步：创建filters资源文件(src/main/filters/dev.properties、test.properties、beta.properties)，其中路径地址/名称任意设置。

dev.properties

 

```
mysql.url=jdbc:mysql://xx.xx.xx.xx:3306/xx
```

 

 

第二步：创建配置文件(src/main/resources/settings.properties)，对第一步配置资源进行使用。

settings.properties

 

```
mysql.url=${mysql.url}
```

 可使用如下命令将配置文件导入到spring容器中

```
<context:property-placeholder location="classpath:settings.properties"/>
```

 

也可在spring配置文件中直接使用(src/main/resources/spring.xml)

spring.xml

 

```
<bean  class="xx.xx.xx.xx.xx.xx">
    <property name="url" value="${mysql.url}" />
</bean>
```

 

第三步：在pom中配置profile

    pom.xml 

```
<profiles>
	<profile>
		<id>dev</id>
		 <build>
			<filters>
				<filter>src/main/filters/dev.properties</filter>
			</filters>
		 </build>
                 <!-- 定义其为默认加载 -->
		 <activation>
			<activeByDefault>true</activeByDefault>
		 </activation>
	</profile>
	<profile>
		<id>test</id>
		 <build>
			<filters>
				<filter>src/main/filters/test.properties</filter>
			</filters>
		 </build>
	</profile>
	<profile>
		<id>beta</id>
		 <build>
			<filters>
				<filter>src/main/filters/beta.properties</filter>
			</filters>
		 </build>
	</profile>
```

 将其添加到pom的&lt;project&gt;标签内部。

 

第四步(关键一步)：maven打包时激活filters过滤。

pom.xml

```
<build>
         <!-- 定义项目打包后的名称 -->
	<finalName>pojo-name</finalName>
	<resources>
		<resource>
                         <!-- 对该目录下的配置build时启用filter 过滤替换-->
			<directory>src/main/resources</directory>
			<filtering>true</filtering>
		</resource>
	</resources>
</build>
```

 

 

第五步：执行打包命令

mvn package -P dev

其中 -P 指定编译的profile

 

问题分享：

在使用过程中，配置与以上配置完全相同，但始终无法对${mysql.url}等参数进行替换，最终导致的问题是，我在eclipse--&gt;properties--&gt;java build path--&gt;source 配置中将src/main/resources默认编译到了src/main/webapp/WEB-INF/classes 目录下(未替换文件-错误文件)，导致在执行mvn 命令时，由于未进行mvn清理，mvn是直接将src/main/webapp/WEB-INF/classes拷贝到了target/obj-name/WEB-INF/下面，而不是经过build filter重新生成的配置文件！解决方案：删除src/main/webapp/WEB-INF/classes下配置文件，让其在mvn package -P dev 时重新生成！