这个问题类似于之前的
one.我试图@Autowire一个Hibernate Session在我的一个Spring-JUnit事务测试中,但是我得到这个异常:
java.lang.IllegalStateException:没有Hibernate会话绑定到线程,并且配置不允许创建非事务性
这是我的JUnit类:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"/applicationContext.xml"}) @TransactionConfiguration(transactionManager="transactionManager") @Transactional public class MyTest { @Qualifier("session") @Autowired private Session session; @Test public void testSomething() { session.get(User.class,"me@here.com"); } }
如果我@Autowire一个SessionFactory并以编程方式获取我的会话(而不是在Spring XML中定义它),每一个都可以正常工作:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"/applicationContext.xml"}) @TransactionConfiguration(transactionManager="transactionManager") @Transactional public class MyTest{ @Qualifier("sessionFactory") @Autowired private SessionFactory sessionFactory; @Test public void testSomething() { Session session = SessionFactoryUtils.getSession(sessionFactory,false); session.get(User.class,"me@here.com"); } }
但是,如果我使用< aop:scoped-proxy />在我的Spring XML中定义了我的会话,我可以让我的原始示例工作.像这样:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd "> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> ... </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionfactorybean"> <property name="dataSource" ref="dataSource" /> <property name="configLocation"><value>classpath:/hibernate.cfg.xml</value></property> <property name="configurationClass"> <value>org.hibernate.cfg.AnnotationConfiguration</value> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> <property name="dataSource" ref="dataSource" /> </bean> <tx:annotation-driven transaction-manager="transactionManager"/> <bean id="session" class="org.springframework.orm.hibernate3.SessionFactoryUtils" factory-method="getSession" scope="prototype"> <constructor-arg ref="sessionFactory" /> <constructor-arg value="false" /> <!-- This is seems to be needed to get rid of the 'No Hibernate Session' error' --> <aop:scoped-proxy /> </bean> </beans>
我的问题是:为什么< aop:scoped-proxy />需要考虑到在单元测试中应该只有一个线程有限的事务上下文?什么是定义我的Hibernate Session bean的正确方法?