@Async
method in @Service
annotated class in standalone Spring Boot application doesn't run asynchronously. What am I doing wrong?
When I run the same method directly from main class (@SpringBootApplication
annotated), it works. Example:
Main class
@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) {
//
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With