spring profile 多环境配置管理

本地、测试、开发、产品等不同环境文件配置

现象

  如果在开发时进行一些数据库测试,希望链接到一个测试的数据库,以避免对开发数据库的影响。

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

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


解决

  现在spring3.1也给我们带来了profile,可以方便快速的切换环境。

  使用也是非常方便。只要在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>
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

  profile的定义一定要在文档的最下边,否则会有异常。整个xml的结构大概是这样

<beans xmlns="..." ...>  
  <bean id="dataSource" ... />  
  <bean ... />  
  <beans profile="...">  
    <bean ...>  
  </beans>  
</beans>
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

激活 profile

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

1、ENV方式:

ConfigurableEnvironment.setActiveProfiles("test")
 
 
  • 1
  • 1

2、JVM参数方式:

  tomcat 中 catalina.bat(.sh中不用“set”) 添加JAVA_OPS。通过设置active选择不同配置文件

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

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

-Dspring.profiles.active="local"
 
 
  • 1
  • 1

3、web.xml方式:

<init-param>
  <param-name>spring.profiles.active</param-name>
  <param-value>production</param-value>
</init-param>
 
 
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4

4、标注方式(junit单元测试非常实用):

@ActiveProfiles({"unittest","productprofile"})转转自:http://blog.csdn.net/WANTAWAY314/article/details/52517798?locationNum=2&fps=1

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值