java在测试用例中重写hibernate sessionfactory的数据源
我在applicationContext中配置了一个hibernate SessionFactoryBean,它已经有一个真正的数据源作为属性。但是我想通过重写已经注入sessionfactory的实际数据源,在我的测试类中使用另一个本地/模拟数据源
主应用程序上下文中的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;
我需要用底部的数据源覆盖注入的数据源
# 1 楼答案
如果spring版本为3.1或更新版本,则可以使用配置文件: 将您的bean声明放入带有profile的bean标记中
然后在测试类中添加“test”作为活动配置文件
最后,在测试类的末尾添加数据源配置