gpt4 book ai didi

spring - 在spring bean中是否有可能有一个可以使用事务的关闭方法?

转载 作者:IT老高 更新时间:2023-10-28 13:57:08 27 4
gpt4 key购买 nike

在 spring bean 的 destroy 方法中,我想执行一些查询来清理数据库中的一些内容。 Spring 似乎无论如何都不允许这样做。

错误总是这样的:

Invocation of destroy method failed on bean with name 'someBean': org.springframework.beans.factory.BeanCreationNotAllowedException: Error creating bean with name 'transactionManager': Singleton bean creation not allowed while the singletons of this factory are in destruction (Do not request a bean from a BeanFactory in a destroy method implementation!)

以下将告诉 spring 在不再需要 bean 后调用 shutdownDestroy。但是,我在尝试使用事务时遇到上述错误。

<bean id="someId" name="someName" class="someClass"
destroy-method="shutdownDestroy"/>

当我使用以下方法启用通用生命周期注释时也是如此:

<bean class="org.springframework. ... .CommonAnnotationBeanPostProcessor"/>

然后用 @PreDestroy 标记方法。该方法也不能使用事务。

有什么办法吗?

编辑:谢谢!我让 bean 实现 SmartLifecycle 并添加以下内容,效果非常好。

private boolean isRunning = false;

@Override
public boolean isAutoStartup() {return true;}

@Override
public boolean isRunning() {return isRunning;}

/** Run as early as possible so the shutdown method can still use transactions. */
@Override
public int getPhase() {return Integer.MIN_VALUE;}

@Override
public void start() {isRunning = true;}

@Override
public void stop(Runnable callback) {
shutdownDestroy();
isRunning = false;
callback.run();
}

@Override
public void stop() {
shutdownDestroy();
isRunning = false;
}

最佳答案

有趣的问题。我会说你应该可以通过 letting your bean implement SmartLifeCycle 做到这一点.

这样,如果您的 int getPhase();方法返回 Integer.MAX_VALUE ,它将在 ApplicationContext 时最先被调用。终于关机了。

引用:

关于spring - 在spring bean中是否有可能有一个可以使用事务的关闭方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5891032/

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