我正在开发一个使用 Spring 3、Hibernate 和 JPA 的应用程序。我有两个类如下:
@Component
class Manager {
@Autowired
Util util;
}
和
@Component
class Util {
@Autowired
Manager manager;
@Scheduled(fixedDelay = 1 * 60 * 1000)
@Transactional(propagation = Propagation.REQUIRED)
public void scheduledMethod(){
// Need to update the database in a transaction
}
}
应用程序上下文的相关部分如下:
<context:component-scan base-package="packageName" />
<tx:annotation-driven />
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="defaultPU" />
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<task:annotation-driven executor="executor" scheduler="scheduler"/>
<task:executor id="executor"
pool-size="10"
queue-capacity="10000"
rejection-policy="CALLER_RUNS"/>
<task:scheduler id="scheduler" pool-size="10"/>
使用此配置,我得到以下异常
javax.persistence.TransactionRequiredException: no transaction is in progress
at org.hibernate.ejb.AbstractEntityManagerImpl.flush(AbstractEntityManagerImpl.java:978)
at sun.reflect.GeneratedMethodAccessor88.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:365)
at com.sun.proxy.$Proxy43.flush(Unknown Source)
at sun.reflect.GeneratedMethodAccessor88.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:240)
at com.sun.proxy.$Proxy43.flush(Unknown Source)
如果我从 Util 类中删除 Manager 类的自动装配,它工作正常。此外,在调试时,我发现即使应用程序上下文文件中存在一些错误,计划的方法也会开始执行。
由于某些遗留原因,我无法避免循环依赖。有人可以帮助为什么在循环依赖的情况下会发生此异常吗?