Spring中的@Async在Service类中不起作用? [英] @Async in Spring doesn't work in Service class?

查看:482
本文介绍了Spring中的@Async在Service类中不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

@Async方法不会异步运行.我在做什么错了?

@Async method in @Service annotated class in standalone Spring Boot application doesn't run asynchronously. What am I doing wrong?

当我直接从主类中运行相同的方法(带注释的@SpringBootApplication)时,它可以工作.示例:

When I run the same method directly from main class (@SpringBootApplication annotated), it works. Example:

主班

@SpringBootApplication
@EnableAsync
public class Application implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        // here when I call downloadAnSave() it runs asynchronously...
        // but when I call downloadAnSave() via downloadAllImages() it does not run asynchronously...
    }

}

和我的服务类(此处异步行为不起作用):

and my service class (and here asynchronous behavior doesn't work):

@EnableAsync
@Service
public class ImageProcessorService implements IIMageProcessorService {

    public void downloadAllImages(Run lastRun) {
        // this method calls downloadAnSave() in loop and should run asynchronously....
    }

    @Async
    @Override
    public boolean downloadAnSave(String productId, String imageUrl) {
        //
    }

}

推荐答案

从同一类中调用异步方法将触发原始方法,而不是被拦截的方法. 您需要使用async方法创建另一个服务,然后从您的服务中调用它.

Calling async method from within the same class would trigger the original method and not the intercepted one. You need to create another service with the async method, and call it from your service.

Spring使用通用批注为您创建的每个服务和组件创建一个代理.只有那些代理包含由方法注释(例如Async)定义的所需行为.因此,不是通过代理而是通过原始的裸类来调用这些方法将不会触发这些行为.

Spring creates a proxy for each service and component you create using the common annotations. Only those proxies contain the wanted behavior defined by the method annotations such as the Async. So, calling those method not via the proxy but by the original naked class would not trigger those behaviors.

这篇关于Spring中的@Async在Service类中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆