我正在使用一个使用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
}
}
申请背景的相关部分如下:
factorybean">
使用此配置,我得到以下异常
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类的自动装配,它可以正常工作.此外,在调试时,我发现即使应用程序上下文文件中存在某些错误,预定方法也会开始执行.
由于某些遗留原因,我无法避免循环依赖.
有人可以帮助解决为什么在循环依赖的情况下发生此异常?
最佳答案
您可以使用@PostConstruct实现此目的
@Component
class Manager {
Util util;
public void setUtil(Util util) {
this.util = util;
}
}
@Component
class Util {
@Autowired
Manager manager;
@PostConstruct
public void init(){
manager.setUtil(this);
}
@Scheduled(fixedDelay = 1 * 60 * 1000)
@Transactional(propagation = Propagation.required)
public void scheduledMethod(){
// Need to update the database in a transaction
}
}