Using Lombok @RequiredArgsConstructor to Replace @Autowired and @Resource in Spring Dependency Injection
The article explains Spring's three dependency injection methods, highlights the drawbacks of field injection, recommends constructor injection, and demonstrates how Lombok's @RequiredArgsConstructor can generate the required constructor to eliminate @Autowired and @Resource annotations, simplifying code and preventing NullPointerExceptions.
Spring provides three ways to inject dependencies: property injection, constructor injection, and setter injection. Field injection using @Autowired or @Resource is discouraged because it can lead to NullPointerExceptions and makes the code harder to test.
Constructor injection forces dependencies to be provided at object creation time, allowing the injected fields to be declared final , which improves immutability and helps avoid circular dependencies. Spring recommends this approach.
Example of property injection:
public class SysUserController extends BaseController {
@Autowired
private ISysUserService userService;
@Resource
private ISysRoleService roleService;
}Example of constructor injection:
public class SysUserController extends BaseController {
private final ISysUserService userService;
private final ISysRoleService roleService;
public SysUserController(ISysUserService userService, ISysRoleService roleService) {
this.userService = userService;
this.roleService = roleService;
}
}Example of setter injection:
public class SysUserController extends BaseController {
private ISysUserService userService;
@Autowired
public void setUserService(ISysUserService userService) {
this.userService = userService;
}
}Lombok offers three annotations to generate constructors: @NoArgsConstructor , @RequiredArgsConstructor , and @AllArgsConstructor . Using @RequiredArgsConstructor together with @Controller creates a constructor that includes all final fields, effectively replacing the need for @Autowired or @Resource on those fields.
@Controller
@RequiredArgsConstructor
public class SysUserController extends BaseController {
private final ISysUserService userService;
private final ISysRoleService roleService;
// other code
}With this Lombok annotation, the generated private constructor injects the required services, eliminating boilerplate, allowing the fields to be final , and preventing null‑pointer issues associated with field injection.
In summary, prefer constructor injection for Spring beans, and use Lombok's @RequiredArgsConstructor to streamline the code while maintaining safety and readability.
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.