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

6 points
Created by:

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

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

package com.example.controllers;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.beans.factory.annotation.Autowired;


@RequiredArgsConstructor(onConstructor = @__(@Autowired))  // <---- required
public class SomeController {

    private final RoleService roleService;    // <----- final makes it @Autowired in the contructor
    private final UsersService usersService;  // <----- final makes it @Autowired in the contructor

    // some code here ...


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.

❤️💻 🙂