It is common when building applications using Spring, to use the @EnableAsync annotation to enable asynchronous executions and with the help of @Async over methods easily make them asynchronous.
@Async has basically two usage rules:
In the example below, there will be no compilation problems, but the method (despite being annotated with @Async) will not execute as desired.
@Slf4j @Service @RequiredArgsConstructor public class HelloService { public String get() { log.info("Chegou!"); print(); return "Ola!"; } @Async @SneakyThrows public void print() { Thread.sleep(Duration.ofSeconds(5)); log.info("Burlado!"); } }
And it is very common for us to wish that, because it is the responsibility of the class, the block of code that must be executed asynchronously remains in it. How to solve?
Simple!
We just need to create another class that helps, for example:
@Service public class AsyncService { @Async public void run(final Runnable runnable) { runnable.run(); } @Async public <O> O run(final Supplier<O> supplier) { return supplier.get(); } }
We do dependency injection of this bean where asynchronous execution is desirable and on top of that, we can make the method private.
@Slf4j @Service @RequiredArgsConstructor public class HelloService { private final AsyncService asyncService; public String get() { log.info("Chegou!"); asyncService.run(this::print); return "Ola!"; } @SneakyThrows private void print() { Thread.sleep(Duration.ofSeconds(5)); log.info("Burlado!"); } }
This small example demonstrates the application of several concepts and resources: Inversion of Control, Dependency Injection, SOLID, Design Pattern, Functional Interfaces.
The above is the detailed content of Burlando o @Async do Spring. For more information, please follow other related articles on the PHP Chinese website!