Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

@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) {
        //
    }

}
like image 405
Artegon Avatar asked Oct 14 '16 11:10

Artegon


1 Answers

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.

like image 158
aviad Avatar answered Oct 13 '22 22:10

aviad