Skip to content
springside edited this page Apr 10, 2012 · 24 revisions

用Profile 统一环境配置

Spring 3.1的功能,以后就不用为了区分Test, Dev, Production环境,搞几个只有细微区别的application.xml, application-test.xml及引用它们的web.xml了。

  1. 首先,将applicationContext.xml中的namespace从3.0升级到3.1.xsd, 然后就可以在文件末尾加入不同环境的定义,比如不同的dataSource
<beans profile="dev">
	<jdbc:embedded-database id="dataSource">
		<jdbc:script location="classpath:com/bank/config/sql/schema.sql"/>
	</jdbc:embedded-database>
</beans>
 
<beans profile="production">
	<jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/datasource"/>
</beans>

2.在web.xml里,你需要定义使用的profile,最聪明的做法是定义成context-param,注意这里定义的是default值,随时可以用环境变量"spring.profiles.active"进行覆盖。在functional-test就使用了这个方法,不再为了定义不同的profile而需要多一个web.xml

	<context-param>
    	    <param-name>spring.profiles.default</param-name>
    	    <param-value>test</param-value>
	</context-param>

3.在用到ApplicationContext的测试用例中,也需要定义

    @ContextConfiguration(locations = { "/applicationContext.xml" })
    @ActiveProfiles("test")
    public class AccountDaoTest extends SpringTxTestCase {
    }

在springside里有演示了production,test,functional三个环境, 大家可以根据实际情况组合自己的环境管理。另外可以与Spring的properties文件加载时可顺位覆盖的特性(放一些不在版本管理中的xx.local.properties文件),支持本地开发环境,Jenkins上的functional test等其他环境。

##配置方式 Spring3.0的精力都在Java Config和Spring EL上,但暂时没看到很适合使用的场景。

配置还是建议老规矩,Dao,Manager, Controller, WebService这些类似的,配置要求不高的Bean就用@Component标注并使用@Autowired注入依赖.其他独立性比较强的就用XML配置并在XML里显式的说明注入关系。

返回参考手册