欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

spring profile 多环境配置管理详解

时间:2021-09-05 09:45:56|栏目:JAVA代码|点击:

 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>

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

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

激活 profile

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

1、ENV方式:

ConfigurableEnvironment.setActiveProfiles("test")

2、JVM参数方式:

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

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

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

-Dspring.profiles.active="local"

3、web.xml方式:

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

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

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

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

上一篇:SpringCloud Eureka服务发现实现过程

栏    目:JAVA代码

下一篇:详解Spring Boot中整合Sharding-JDBC读写分离示例

本文标题:spring profile 多环境配置管理详解

本文地址:http://www.codeinn.net/misctech/172825.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有