maven整合spring profile实现多环境自动切换

现象

如果在开发时进行一些数据库测试,希望链接到一个测试的数据库,以避免对开发数据库的影响。又或者当我们要打包项目发布到生产环境的时候,我们只想打包生产环境的配置而不想打包开发或者测试环境的配置,各种此类的需求,让我希望有一个简单的切换开发环境的好办法。

多环境自动切换整合步骤

  1. resources目录下添加不同环境的配置文件

  2. applicationContext文件增加profile配置

<!-- 开发环境配置文件 -->
<beans profile="dev">
    <import resource="classpath:dev/remote-sevlet.xml"/>
    <context:property-placeholder location="classpath:dev/*.properties"/>
</beans>
<!-- 测试环境配置文件 -->
<beans profile="test">
    <import resource="classpath:test/remote-sevlet.xml"/>
    <context:property-placeholder location="classpath:test/*.properties"/>
</beans>
<!-- 生产环境配置文件 -->
<beans profile="prod">
    <import resource="classpath:prod/remote-sevlet.xml"/>
    <context:property-placeholder location="classpath:prod/*.properties"/>
</beans>

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

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

spring 为我们提供了大量的激活 profile 的方法:

(1)通过代码来激活

ConfigurableEnvironment.setActiveProfiles

(2)通过系统环境变量、JVM参数、servlet上下文参数来定义 spring.profiles.active 参数激活 profile。

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

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

2.2 IDEA中Run –>Edit configuration–>Arguments–> VM arguments中添加。

2.3 web.xml方式:

<init-param>
  <param-name>spring.profiles.active</param-name>
  <param-value>production</param-value>
</init-param>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容