gpt4 book ai didi

java - Spring Scheduler - 当存在循环依赖时,计划的方法不会在事务中启动

转载 作者:搜寻专家 更新时间:2023-10-31 08:03:48 25 4
gpt4 key购买 nike

我正在开发一个使用 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 类的 Autowiring ,它就可以正常工作。此外,在调试时我发现即使应用程序上下文文件中存在一些错误,计划的方法也会开始执行。

由于某些遗留原因,我无法避免循环依赖。有人可以帮助解释为什么在循环依赖的情况下会出现此异常吗?

最佳答案

您可以使用@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
}
}

关于java - Spring Scheduler - 当存在循环依赖时,计划的方法不会在事务中启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17830837/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com