Skip to content
springside edited this page Mar 9, 2012 · 24 revisions

用Profile 统一环境配置

Spring 3.1的功能,以后就不用为了区分Test, Dev, Production环境,搞几个只有细微区别的application.xml, application-test.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:script location="classpath:com/bank/config/sql/test-data.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

	<context-param>
    	    <param-name>spring.profiles.active</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两个环境,当然实际还有本人开发环境,集成测试环境等等一堆环境,需要大家有效的利用spring的Profile功能,与Spring的properties文件加载时可顺位覆盖的特性(放一些不在版本管理中的local properties文件),灵活的组合自己的环境管理。

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

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

返回参考手册