在spring bean中,是否可以有一种可以使用事务的关闭方法? [英] In a spring bean is it possible to have a shutdown method which can use transactions?
问题描述
在spring bean的destroy方法中,我想执行一些查询以清理数据库中的某些内容.我似乎无法找到Spring允许的任何方式.
In the destroy method of a spring bean I want to execute some queries to clean up some stuff in the database. Spring doesn't seem to allow this by any means I can find.
错误总是类似:
调用destroy方法失败 名称为"someBean"的bean: org.springframework.beans.factory.BeanCreationNotAllowedException: 使用名称创建bean时出错 'transactionManager':单例bean 不允许创建 这家工厂的单身人士在 销毁(不要请求bean 从BeanFactory中使用destroy方法 实施!)
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.但是,尝试使用事务时出现上述错误.
The following will tell spring to call shutdownDestroy after the bean is no longer needed. But, I get the above error when trying to use transactions.
<bean id="someId" name="someName" class="someClass"
destroy-method="shutdownDestroy"/>
当我使用以下方法启用通用生命周期注释时,情况也是如此:
The same is true when I enable common lifecycle annotations using:
<bean class="org.springframework. ... .CommonAnnotationBeanPostProcessor"/>
,然后用@PreDestroy
标记该方法.该方法也不能使用事务.
and then mark the method with @PreDestroy
. That method can't use transactions either.
有什么办法吗?
谢谢!我让bean实现了SmartLifecycle并添加了以下内容,并且效果很好.
Thanks! I had the bean implement SmartLifecycle and adding the following and it works very nicely.
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;
}
推荐答案
Interesting Question. I'd say you should be able to do it by letting your bean implement SmartLifeCycle
.
这样,如果您的int getPhase();
方法返回Integer.MAX_VALUE
,它将在ApplicationContext
最终关闭时成为第一个被调用的对象.
That way, if your int getPhase();
method returns Integer.MAX_VALUE
, it will be among the first to be called when the ApplicationContext
finally shuts down.
参考:
- 3.6.1.5 Startup and shutdown callbacks
SmartLifeCycle
javadocs
这篇关于在spring bean中,是否可以有一种可以使用事务的关闭方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!