您的位置:首页 > 其它

Maven 使用profile来区分开发、测试、生产环境

2017-04-17 00:35 609 查看
Maven允许用户提供自定义的Profile(配置集)来应对在不同场景下配置不同的问题。这样做的好处是将配置做隔离,在打包时,只需要选中的Profile package就行。实现方式是结合Maven的过滤器来处理占位符的替换

来看XML配置

<!--定义配置文件-->
<profiles>
<profile>
<id>dev</id>
<properties>
<env>dev</env>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>test</id>
<properties>
<env>test</env>
</properties>
</profile>
<profile>
<id>release</id>
<properties>
<env>release</env>
</properties>
</profile>
<profile>
<id>product</id>
<properties>
<env>product</env>
</properties>
</profile>
</profiles>
<build>
<filters>
<!--这里定义配置资源的目录,并且根据变量不同来选取不同的目录-->
<filter>src/main/config/${env}.properties</filter>
</filters>
<resources>
<resource>
<!--这里定义需要处理的配置资源路径-->
<directory>src/main/resources</directory>
<!--启用过滤-->
<filtering>true</filtering>
</resource>
</resources>
</build>这样定义完以后,就可以在Maven栏中看到这些配置



默认dev是勾选的,因为配置了activeByDefault为true。

新建prop.properties文件

environment=${environment}

在目录src/java/main/config新建四个配置文件
dev.properties

environment=dev
test.properties

environment=test
release.properties

environment=releaseproduct.properties
environment=product

bean.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:property-placeholder location="prop.properties"/>
<bean id="profileTest" class="org.zheng.profile.ProfileTest">
<property name="environment" value="${environment}"/>
</bean>
</beans>
测试代码

public class ProfileTest {
private String environment;

public String getEnvironment() {
return environment;
}

public void setEnvironment(String environment) {
this.environment = environment;
}

public static void main(String[] args) throws IOException {
ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
ProfileTest profileTest = (ProfileTest)ac.getBean("profileTest");
System.out.println("env="+profileTest.getEnvironment());
}
}

执行查看输出结果:



由此看到,变量被替换为dev.properties中的值。构建maven,也将自动替换格式为"${xxx}"为当前激活的配置集中的内容。

完整项目地址:

https://github.com/difffate/JavaProject
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  maven profile