@Async in Spring doesn't work in Service class?

前端 未结 2 383
礼貌的吻别
礼貌的吻别 2021-01-20 07:36

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

When I

相关标签:
2条回答
  • 2021-01-20 08:01

    Workaround is:

    @EnableAsync
    @Service("ip-service")
    public class ImageProcessorService implements IIMageProcessorService {
        
        @Autowired
        @Qualifier("ip-service")
        ImageProcessorService ipService;
    
        public void downloadAllImages(Run lastRun) {
            // this method calls downloadAnSave() in loop and should run asynchronously....
            ipService.downloadAnSave(productId, imageUrl);
        }
    
        @Async
        @Override
        public boolean downloadAnSave(String productId, String imageUrl) {
            //
        }
    }
    

    With such approach you call method of proxy, not the class instance. The same approach can be used with other tools working with proxies, e.g. @Transactional etc.

    0 讨论(0)
  • 2021-01-20 08:11

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

    0 讨论(0)
提交回复
热议问题