Languages
[Edit]
EN

Spring Boot - inject @Autowired controller fields automatically as constructor arguments with Lombok

6 points
Created by:
Brian-Tompset
491

In this short article, we would like to show how to use Lombok to automatically generate a constructor that gets all @Autowired controller fields as arguments.

Quick solution:

  1. Add @RequiredArgsConstructor(onConstructor = @__(@Autowired)) annotation to controller,
  2. Add final keyword to each controller field that you want to be @Autowired.

Note: final keyword forces Lombok to add the field as controller argument, @__(@Autowired) tells Lombok to prefix arguments with @Autowired annotation.

 

Practical example

Edit

In the below example, Lombok will generate controller constructor with 2 arguments:
@Autowired RoleService roleService and @Autowired UserService userService.

 

1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join