在工作中,开发环境一般和生产环境不同,比如开发Java web应用时我们一般喜欢使用Tomcat等轻量型容器,而在生产环境一般使用像Weblogic这样的商业重量级容器;单元测试的时候大家喜欢直接使用内存数据库,而生产环境则使用像Oracle这样的商业数据库。对于这类问题我们一般需要提供不同的配置信息,甚至写不同的构建脚本来支持持续集成工作,如果我们正使用spring框架进行开发,spring 从3.1版本开始为我们提供了一个可选方案,即profile。
什么是spring profile?简单讲profile就是一组配置,不同profile提供不同组合的配置,程序运行时可以选择使用哪些profile来适应环境。spring bean 配置是使用spring框架进行开发的一项重要工作,有了profile可以让开发和测试工作更加条理,下面是用标注配置的一个profile示例:
1
2
3
4
5
|
@Configuration @Profile (value= "productprofile" )
public class ProductConfig {
... } |
profile当然同时支持XML和Java文件标注,可用于class级别也可用于配置文件级别,或者beans级别。比如我们创建一个unittest profile用于指明单元测试使用,而某个class TestA只是测试有用,那么我们可以将其标注unittest profile,这样如果unittest profile没有启用时TestA是不会被spring上下文解析。profile主要用于对bean 配置进行分类贴标签,笔者建议先将不同环境的配置分类放于不同XML配置文件(或者java配置类),然后再给各个配置文件加全局的profile属性,避免给单个类贴标签,另外profile确实很灵活,一个配置文件可以贴多个profile标签,如
1
|
< beans profile = "p1,p2" >
|
spring提供多种启用profile的方式:
1
2
3
4
5
6
7
8
9
|
1 .ENV方式: ConfigurableEnvironment.setActiveProfiles( "unittest" )
2 .JVM参数方式: -Dspring.profiles.active= "unittest"
3 .web.xml方式:
<init-param> <param-name>spring.profiles.active</param-name>
<param-value>production</param-value>
</init-param> 4 .标注方式(junit单元测试非常实用):
@ActiveProfiles({ "unittest" , "productprofile" })
|
附件中给了个例子通过启用不同profile来使用不同的datasource,供大家一起学习参考,谢谢!