Spring3.1新属性管理API:PropertySource、Environment、Profile(三)

2014-11-24 03:26:58 · 作者: · 浏览: 4
ng3

通过如上方式可以实现不同的环境有不同的属性配置,但是如果我们想不同的环境加载不同的Bean呢,比如测试机/正式机环境可能使用远程方式访问某些API,而开发机环境使用本地方式进行开发,提高开发速度,这就需要profile了。

通过在beans标签上加上profile属性,这样当我们激活相应的profile时,此beans标签下的bean就会注册,如下所示:

  


    
     
     
   


    
     
     
   


  

启动应用时设置相应的“spring.profiles.active”即可。另外,如果想指定一个默认的,可以使用 指定(如果不是default,可以通过“spring.profiles.default”指定)。

@Profile()

Java Config方式的Profile,功能等价于XML中的 ,使用方式如下:

@Profile("dev")
@Configuration
@PropertySource(value = "classpath:resources.properties", ignoreResourceNotFound = false)
public class AppConfig {

    @Bean
    public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }
}

Spring4提供了一个新的@Conditional注解,请参考http://jinnianshilongnian.iteye.com/blog/1989379。

@ActiveProfiles()

在测试时,有时候不能通过系统启动参数/上下文参数等指定Profile,此时Spring测试框架提供了@ActiveProfiles()注解,示例如下:

@ActiveProfiles("test")
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = GenericConfig.class)
public class GenricInjectTest {
……
}

通过这种方式,我们就激活了test profile。

到此整个Spring的属性管理API就介绍完了,对于属性管理,核心是Environment,所以以后请使用Environment来进行属性管理吧。

欢迎加入spring群134755960进行交流。

http://sishuok.com/forum/blogPost/list/7936.html