我在 applicationContext 中配置了一个 hibernate SessionFactoryBean,它已经有一个真正的数据源作为属性。但我想通过覆盖已经注入(inject)到 sessionfactory 的实际数据源来在我的测试类中使用另一个本地/模拟数据源。
主应用Context中的bean定义是这样的。
<bean id="SessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
abstract="false" scope="singleton" lazy-init="default" autowire="default">
<property name="dataSource" ref="pcfDataSource"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">$`db.hibernate.dialect} </prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
<prop key="hibernate.cache.use_second_level_cache">true</prop>
<prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory</prop>
</props>
</property>
</bean>
我的测试用例中有一个像这样的本地数据源:
template = InitializeDataSource.getInitializedDataSource();
DataSource dataSource = template.getDataSource;
我需要用底部的数据源覆盖注入(inject)的数据源
最佳答案
如果您的 Spring 版本是 3.1 或更高版本,您可以使用配置文件: 将您的 bean 声明放入带有配置文件的 beans 标签内
<beans profile="!test">
<bean id="pcfDataSource" ...>
...
</bean>
</beans>
然后在您的测试类中添加“test”作为您的 Activity 配置文件
@ActiveProfiles("test")
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "app-context.xml")
public class SampleTest
最后,在测试类的末尾添加数据源配置
@Test
public void someTest() {
...
}
@Configuration
public class MockDataSourceConfig {
@Bean
public DataSource pcfDataSource() {
Template template = InitializeDataSource.getInitializedDataSource();
return template.getDataSource;
}
}
关于java - 在测试用例中覆盖 hibernate sessionfactory 的数据源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33881748/