[英]Dependency Injection without constructor in Spring Boot
I am beginner at Spring / Spring Boot and I have a look at some Spring / Spring Boot projects and realized that, in some of them DI is applied using constructor as shown below:
@RestController
@RequestMapping("/api/v1/core")
public class DemoController {
private final SalaryService salaryService;
private final EmployeeService employeeService;
public DemoController(SalaryService salaryService, EmployeeService employeeService) {
this.salaryService = salaryService;
this.employeeService = employeeService;
}
}
然而,在一些项目中,DI是通过注解来应用的,并且代码被简化了。 是否可以在 Spring 或 Spring Boot 中使用注释并通过删除构造函数来简化代码? 如果是这样,那是否适用于服务、存储库和 Controller?
您可以通过添加 @RequiredArgsConstructor 来使用 Lombok
@RestController
@RequestMapping("/api/v1/core")
@RequiredArgsConstructor
public class DemoController {
private final SalaryService salaryService;
private final EmployeeService employeeService;
}
是的,它适用于 Service、Repository 和 Controller。 您还可以在字段或设置器上使用@Autowired 注释,但这种方式不是首选。 更多细节在这里: Spring @Autowire on Properties vs Constructor
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.