是否可以有一种可以使用事务的关闭方法

是否可以有一种可以使用事务的关闭方法

本文介绍了在spring bean中,是否可以有一种可以使用事务的关闭方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

在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.

错误总是类似:

以下内容将告诉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;
}

推荐答案

有趣的问题.我说您应该可以通过让您的bean实现SmartLifeCycle .

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.

参考:

这篇关于在spring bean中,是否可以有一种可以使用事务的关闭方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 14:11