Home > Java > javaTutorial > body text

Burlando o @Async do Spring

王林
Release: 2024-09-12 10:21:00
Original
1041 people have browsed it

Burlando o @Async do Spring

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:

  • the annotated method must be public
  • the method invoker cannot be from the same class

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!");
    }
}
Copy after login

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();
    }
}
Copy after login

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!");
    }
}
Copy after login

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!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!