spring profiles实现不同的环境配置的一键切换

在开发的时候通常会碰到一下的场景:一个分支,在开发环境运行测试的时候连开发数据库(或者linux相关路劲配置),在本地运行测试

的时候连本地数据库(windows下相关路径测试),那么简单粗爆的方法就是同一个属性写几条不同个值,在相应的环境做对应的注释。

在spring3.1之后有了profile,可以一键开关式的快速的切换环境。

profile的主要配置

配置环境

在applicationContext.xml(spring下上文配置文件)中添加下边的内容,就可以了

<beans profile="develop">  
        <context:property-placeholder location="classpath*:jdbc-develop.properties"/>  
    </beans>  
    <beans profile="production">  
        <context:property-placeholder location="classpath*:jdbc-production.properties"/>  
    </beans>  
    <beans profile="test">  
        <context:property-placeholder location="classpath*:jdbc-test.properties"/>  
    </beans>


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

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


我通过给不同的环境,引入不同的properties来设置不同的属性,你也可以直接在bean里进行定义一些特殊的属性,比如下边这样,在test的时候,初始化数据库与默认数据。(代码摘录:springside)

<!-- unit test环境 -->  
    <beans profile="test">  
        <context:property-placeholder ignore-resource-not-found="true"  
            location="classpath*:/application.properties,  
                      classpath*:/application.test.properties" />      
          
        <!-- Simple连接池 -->  
        <bean id="dataSource" class="org.springframework.jdbc.datasource.SimpleDriverDataSource">  
            <property name="driverClass" value="${jdbc.driver}" />  
            <property name="url" value="${jdbc.url}" />  
            <property name="username" value="${jdbc.username}" />  
            <property name="password" value="${jdbc.password}" />  
        </bean>  
  
        <!-- 初始化数据表结构 与默认数据-->  
        <jdbc:initialize-database data-source="dataSource" ignore-failures="ALL">  
            <jdbc:script location="classpath:sql/h2/schema.sql" />  
            <jdbc:script location="classpath:data/import-data.sql" encoding="UTF-8"/>  
        </jdbc:initialize-database>  
    </beans>  

切换环境

  在web.xml中添加一个context-param来切换当前环境:

<context-param>  
    <param-name>spring.profiles.active</param-name>  
    <param-value>develop</param-value>  
</context-param> 


 如果是测试类可以使用注解来切换:

@ActiveProfiles("test")
@RunWith(SpringJUnit4ClassRunner.class)  
@ContextConfiguration(locations = "classpath:applicationContext.xml")  
@ActiveProfiles("test")  
public class DictionaryServiceTest extends AbstractTransactionalJUnit4SpringContextTests  

 你可以写一个基类来写这个注解,然后让你们测试类都继承这个测试基类,会很方便。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值