EN
Spring Boot - inject @Autowired controller fields automatically as constructor arguments with Lombok
6 points
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:
|
Note:
final
keyword forces Lombok to add the field as controller argument,@__(@Autowired)
tells Lombok to prefix arguments with@Autowired
annotation.
In the below example, Lombok will generate controller constructor with 2 arguments:
@Autowired RoleService roleService
and @Autowired UserService userService
.
xxxxxxxxxx
1
package com.example.controllers;
2
3
import lombok.RequiredArgsConstructor;
4
import org.springframework.stereotype.Controller;
5
import org.springframework.beans.factory.annotation.Autowired;
6
7
import com.example.services.RoleService;
8
import com.example.services.UsersService;
9
10
11
onConstructor = ( )) // <---- required (
12
public class SomeController {
13
14
private final RoleService roleService; // <----- final makes it @Autowired in the contructor
15
private final UsersService usersService; // <----- final makes it @Autowired in the contructor
16
17
// some code here ...
18
}