独立 Spring Boot 应用程序中 @Async 注释类中的 @Service 方法不会异步运行。我究竟做错了什么?

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

主类

@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...
    }

}

和我的 服务类 (这里异步行为不起作用):
@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方法创建另一个服务,然后从您的服务中调用它。

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

关于java - Spring 中的 @Async 在 Service 类中不起作用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40042505/

10-10 08:39
查看更多