DEV Community

Leila Farias
Leila Farias

Posted on

4

Injeção de dependências com Spring e Lombok

Já conhecemos algumas formas de injetar objetos numa classe, dentro de um projeto Spring, como anotar com @Autowired um atributo da classe ou um construtor.

Porém, recentemente, aprendi mais 2 formas interessantes que eliminam parte do código fonte, que vou mostrar a seguir, ambas usando Lombok.

1ª forma: @AllArgsConstructor

O Lombok possui a annotation AllArgsConstructor que cria um construtor com todos os atributos da classe. Porém, usando o atributo da annotation onConstructor, permite você especificar qual annotation deve ser incluída no construtor gerado:

@RestController
@AllArgsConstructor(onConstructor = @__(@Autowired))
public class UserController {

    private UserService userService;
    private Profession professionService;

    /*
     * Ao invés de usar assim:
     *
     * @Autowired
     * private UserService userService;
     *
     * @Autowired
     * private Profession professionService;
     *
    */
}
Enter fullscreen mode Exit fullscreen mode

2ª forma: @RequiredArgsConstructor

Basta anotar a classe com a annotation @RequiredArgsConstructor, que cria um construtor com todos os atributos final da classe. Assim, o Spring injeta pra gente as dependências obrigatórias.

@RestController
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;
    private final Profession professionService;

    /*
     * Ao invés de usar assim:
     *
     * @Autowired
     * private UserService userService;
     *
     * @Autowired
     * private Profession professionService;
     *
    */
}
Enter fullscreen mode Exit fullscreen mode

Lembrete!

Criar construtores em classes abstratas te obriga a criar construtores nas classes filhas chamando o construtor da classe mãe.

Referências

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

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

AWS Security LIVE!

Hosted by security experts, AWS Security LIVE! showcases AWS Partners tackling real-world security challenges. Join live and get your security questions answered.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️