1.介绍

    profile可以让我们定义一系列的配置信息,然后指定其激活条件,我们再项目开发中经常要遇到 开发环境和 生产环境的切换,两个环境配置信息由所不同,例如:连接DB信息。我常用的一种办法就是在部署项目时手动修改。maven 的profile提供 自动切换机制



2.配置



2.1 POM配置

       案例地址: 



2.1.1 添加profiles元素

        id 确定当前profile标识, test 代表 测试环境 或者 开发环境, product 代表 生成环境,

  activation 确定是当前profile 是否默认优先加载,true 为默认加载,false 为 否, properties里配置了很多属性元素,这些属性名称是自定义。和src/java/resources properties文件定义名称保持一致.          

<profiles>
		<profile>
			<id>test</id>
			<activation>
				<activeByDefault>true</activeByDefault>
			</activation>
			<properties>
				<active.profile.id>test</active.profile.id>
				<db.url>jdbc:mysql://xx.xx.xx.xxx:3306/cms2?useUnicode=true&autoReconnect=true&characterEncoding=UTF8</db.url>
				<db.user>test</db.user>
				<db.password>test</db.password>
				<mq.address>xx.x.xx.x:61616</mq.address>
				<cms.url>http://10.1.30.225/cms2/compile.action</cms.url>
			</properties>
		</profile>

		<profile>
			<id>product</id>
			<activation>
				<activeByDefault>false</activeByDefault>
			</activation>
			<properties>
				<active.profile.id>product</active.profile.id>
				<db.url>jdbc:mysql://bjct.cms2.w.qiyi.db:6080/cms2?useUnicode=true&autoReconnect=true&characterEncoding=UTF8</db.url>
				<db.user>production</db.user>
				<db.password>production</db.password>
				<mq.address>xx.xx.xxx:61616</mq.address>
				<cms.url>http://xx.xx.xxx/compile.action</cms.url>
			</properties>
		</profile>
	</profiles>



2.1.2 添加resources元素

         当中 filtering 标识 是否过滤,需要为true

<resources>
<resource>
<directory>src/main/resources </directory>
<includes>
<include>**/*.xml </include>
<include>**/*.properties </include>
</includes>
<filtering>true </filtering>
</resource>
</resources>



2.2 Properties 配置

    案例地址:

这里面配置key需要和pom下properties定义名称一致,值要${}标识,便于maven在build的时候根据配置环境替换实值。 

jdbc.driver = com.mysql.jdbc.Driver
db.url = ${db.url}
db.user = ${db.user}
db.password = ${db.password}
mq.address = ${mq.address}
cms.url = ${cms.resource.compile.url}



3.执行

   以上配置完成后,进入工程目录。对工程进行构建,其中参数 -P 就是指定当前构建环境的,pom默认配置环境是 test(测试环境), -P product 为 生产环境。  键入命令:

   mvn clean package -Dmaven.test.skip=true -P product

    或者

   mvn clean package -Dmaven.test.skip

此时进入target/jdbc.properties 看下配置文件实值是否覆盖到配置文件上了.如果properties内值被pom配置替换,说明配置成功,这样是不很爽,以后发布线上环境只要加一个-P pro 就可以轻松切换.



4.其它配置方法

  maven profile 提供很多配置方法,功能相对比较全。这里再介绍一种配置形式。 有一种情况我习惯把值写到properties文件里,还不能习惯写到pom.xml下维护,这种情况怎么办了. 我们会在src/java/resources配置两个文件.env.dev.properties 和 env.pro.properties. 这两个文件一个开发配置文件,一个生产配置文件. 我们可以通过maven 指定加载哪个配置文件。实现步骤基本和上面一样,看一下profiles, resources配置:

[env.dev.properties ] 
   
 [env.pro.properties] 
  
 [pom.xml]