在测试类中基于 profile 加载测试 bean
从 Spring 3.2 以后,Spring 开始支持使用 @ActiveProfiles 来指定测试类加载的配置包,比如您的配置文件只有一个,但是需要兼容生产环境的配置和单元测试的配置,那么您可以使用 profile 的方式来定义 beans,如下:
清单 10. Spring-db.xml
 <beans xmlns="http://www.Springframework.org/schema/beans"
	 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.Springframework.org/schema/beans 
 ">
<beans profile="test"> 
 <bean> 
 <property value="org.hsqldb.jdbcDriver" />
<property value="jdbc:hsqldb:hsql://localhost" />
<property value="sa"/>
<property value=""/>
</bean> 
</beans>
<beans profile="production"> 
 <bean>
<property value="org.hsqldb.jdbcDriver" />
<property value="jdbc:hsqldb:hsql://localhost/prod" />
<property value="sa"/>
<property value=""/>
</bean> 
 </beans> 
 <beans profile="test,production"> 
 <bean>
<property ref="datasource"></property>
</bean>
<bean init-method="init">
</bean> 
 <bean depends-on="initer">
<property ref="datasource"/>
</bean>
<bean>
</bean>
<bean/>
</beans> 
 </beans> 
   
 
上面的定义,我们看到:
在 XML 头中我们引用了 Spring 3.2 的 beans 定义,因为只有 Spring 3.2+ 才支持基于 profile 的定义
在 <beans> 根节点下可以嵌套 <beans> 定义,要指定 profile 属性,这个配置中,我们定义了两个 datasource,一个属于 test profile,一个输入 production profile,这样,我们就能在测试程序中加载 test profile,不影响 production 数据库了
在下面定义了一些属于两个 profile 的 beans,即 <beans profile=”test,production”> 这样方便重用一些 bean 的定义,因为这些 bean 在两个 profile 中都是一样的
清单 11. AccountServiceTest.Java
 @RunWith(SpringJUnit4ClassRunner.class) 
 @ContextConfiguration("/config/Spring-db.xml") 
 @Transactional 
 @ActiveProfiles("test") 
 public class AccountServiceTest { 
 ... 
 } 
   
 
注意上面的 @ActiveProfiles,可以指定一个或者多个 profile,这样我们的测试类就仅仅加载这些名字的 profile 中定义的 bean 实例。