spring3.1 profile 配置不一样的环境

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

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

各类此类的需求,让我但愿有一个简单的切换开发环境的好办法,曾经在ROR的时候就很喜欢舒服。spring

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

一、配置环境app

使用也是非的方便。只要在applicationContext.xml中添加下边的内容,就能够了测试

<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的结构大概是这样的,
spa

    我经过给不一样的环境,引入不一样的properties来设置不一样的属性,你也能够直接在bean里进行定义一些特殊的属性,好比下边这样,在test的时候,初始化数据库与默认数据.日志

二、切换环境code

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

<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

 你能够写一个基类来写这个注解,而后让大家测试类都继承这个测试基类,会很方便。

相关文章
相关标签/搜索