Spring @Async被忽略了

Ari*_*iod 14 java spring

我在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
    }
}
Run Code Online (Sandbox Code Playgroud)

NotificationClient内部具有在它接收到来自另一系统的通知的线程.它接受一个NotificationProcessor构造函数,它基本上是将对通知进行实际处理的对象.

在上面的代码中,我将Spring bean作为处理器,并尝试使用@Async注释异步处理通知.但是,似乎通知在与使用的通道相同的线程中处理NotificationClient.实际上,@Async被忽略了.

我在这里错过了什么?

Ral*_*lph 31

@Async只要您不使用真正的AspectJ编译时或运行时编织 ,当@Transactional通过this(on when @Async用于私有方法*)调用该方法时,(以及其他类似的注释)将不起作用.

*私有方法的事情是:当方法是私有的,那么它必须通过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
    }
}
Run Code Online (Sandbox Code Playgroud)

另请参阅以下答案:Spring @Transactional属性是否适用于私有方法? - 这是同样的问题