小编典典

Spring中的@Async在Service类中不起作用?

spring-boot

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

当我直接从主类(带@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) {
        //
    }

}

阅读 2850

收藏
2020-05-30

共1个答案

小编典典

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

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

2020-05-30