[英]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.