DEV Community

Igor Rudel
Igor Rudel

Posted on

Burlando o @Async do Spring

É comum na construção de aplicações utilizando Spring, utilizarmos a anotação de @EnableAsync para habilitar execuções assíncronas e com o auxílio da @Async sobre os métodos facilmente torná-los assíncronos.

A @Async possui basicamente duas regras de utilização:

  • o método anotado deve ser público
  • o invocador do método não pode ser da mesma classe

No exemplo abaixo, não haverá problemas de compilação, porém o método (apesar de anotado com @Async) não terá a execução como o desejado.

@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!");
    }
}
Enter fullscreen mode Exit fullscreen mode

E é muito comum desejarmos que, por ser responsabilidade da classe, o bloco de código que deve ser executado assíncronamente se mantenha nela. Como resolver?

Simples!

Basta criarmos outra classe que auxilie, por exemplo:

@Service
public class AsyncService {

    @Async
    public void run(final Runnable runnable) {
        runnable.run();
    }
}
Enter fullscreen mode Exit fullscreen mode

Fazermos a injeção de dependência dessa bean onde é desejável a execução assíncrona e ainda por cima, poder tornar o método privado.

@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!");
    }
}
Enter fullscreen mode Exit fullscreen mode

Esse pequeno exemplo, demonstra a aplicação de vários conceitos e recursos: Inversão de Controle, Injeção de Dependência, SOLID, Design Pattern, Interfaces Funcionais.

Image of AssemblyAI tool

Transforming Interviews into Publishable Stories with AssemblyAI

Insightview is a modern web application that streamlines the interview workflow for journalists. By leveraging AssemblyAI's LeMUR and Universal-2 technology, it transforms raw interview recordings into structured, actionable content, dramatically reducing the time from recording to publication.

Key Features:
🎥 Audio/video file upload with real-time preview
🗣️ Advanced transcription with speaker identification
⭐ Automatic highlight extraction of key moments
✍️ AI-powered article draft generation
📤 Export interview's subtitles in VTT format

Read full post

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay