spring profile 多环境配置管理

现象

  若是在开发时进行一些数据库测试,但愿连接到一个测试的数据库,以免对开发数据库的影响。html

  开发时的某些配置好比log4j日志的级别,和生产环境又有所区别。git

  各类此类的需求,让我但愿有一个简单的切换开发环境的好办法。web

解决

  如今spring3.1也给咱们带来了profile,能够方便快速的切换环境。spring

  使用也是很是方便。只要在applicationContext.xml中添加下边的内容,就能够了数据库

<!-- 开发环境配置文件 -->
    <beans profile="test">
        <context:property-placeholder location="/WEB-INF/test-orm.properties" />
    </beans>

    <!-- 本地环境配置文件 -->
    <beans profile="local">
        <context:property-placeholder location="/WEB-INF/local-orm.properties" />
    </beans> 

  profile的定义必定要在文档的最下边,不然会有异常。整个xml的结构大概是这样tomcat

<beans xmlns="..." ...>  
  <bean id="dataSource" ... />  
  <bean ... />  
  <beans profile="...">  
    <bean ...>  
  </beans>  
</beans> 

激活 profile

在web.xml里定义使用的profile,最聪明的作法是定义成context-param,注意这里定义的是default值,在非生产环境,能够用系统变量"spring.profiles.active"进行覆盖。app

<context-param>  
  <param-name>spring.profiles.default</param-name>  
  <param-value>production</param-value>  
</context-param> 

 

spring 为咱们提供了大量的激活 profile 的方法,能够经过代码来激活,也能够经过系统环境变量、JVM参数、servlet上下文参数来定义 spring.profiles.active 参数激活 profile,这里咱们经过定义 JVM 参数实现。eclipse

一、ENV方式

ConfigurableEnvironment.setActiveProfiles("test") 

二、JVM参数方式

  tomcat 中 catalina.bat(.sh中不用“set”) 添加JAVA_OPS。经过设置active选择不一样配置文件单元测试

set JAVA_OPTS="-Dspring.profiles.active=test" 

  eclipse 中启动tomcat。项目右键 run as –> run configuration–>Arguments–> VM arguments中添加。local配置文件没必要上传git追踪管理测试

-Dspring.profiles.active="local" 

三、web.xml方式

<init-param>
  <param-name>spring.profiles.active</param-name>
  <param-value>production</param-value>
</init-param>

四、标注方式

junit单元测试很是实用

@ActiveProfiles({"unittest","productprofile"})

 参考资料

https://www.cnblogs.com/pangguoming/p/5888871.html

http://nassir.iteye.com/blog/1535799/

相关文章
相关标签/搜索