Spring @Async被忽略了
我在Spring中异步调用方法时遇到麻烦,因为调用程序是一个从外部系统接收通知的嵌入式库。 代码如下所示:
@Service public class DefaultNotificationProcessor implements NotificationProcessor { private NotificationClient client; @Override public void process(Notification notification) { processAsync(notification); } @PostConstruct public void startClient() { client = new NotificationClient(this, clientPort); client.start(); } @PreDestroy public void stopClient() { client.stop(); } @Async private void processAsync(Notification notification) { // Heavy processing } }
NotificationClient
内部有一个线程,在该线程中,它接收来自另一个系统的通知。 它在其构造函数中接受NotificationProcessor
,它基本上是将对通知进行实际处理的对象。
在上面的代码中,我将Spring bean作为处理器,并尝试使用@Async
批注异步处理通知。 但是,看起来通知是在与NotificationClient
使用的线程相同的线程中处理的。 实际上, @Async
被忽略了。
我在这里想念的是什么?
只要您不使用真正的AspectJ编译时或运行时编织,当通过this
方法调用该方法时( @Async
用于私有方法*), @Async
(以及@Transactional
和其他类似的注释)将不起作用。
*私有方法的事情是:当方法是私有的,那么它必须通过this
调用 – 所以这更多的是后果然后原因
所以改变你的代码:
@Service public class DefaultNotificationProcessor implements NotificationProcessor { @Resource private DefaultNotificationProcessor selfReference; @Override public void process(Notification notification) { selfReference.processAsync(notification); } //the method must not been private //the method must been invoked via a bean reference @Async void processAsync(Notification notification) { // Heavy processing } }
另请参阅以下答案: Spring @Transactional属性是否适用于私有方法? – 这是同样的问题