为什么人们使用 @Autowired 进行构造函数注入

Ale*_*Man 2 java spring dependency-injection autowired

我看到很多人@Autowired在构造函数中使用注释来注入依赖项,如下所示

@Service
public class Employee {

 private EmployeeService employeeService;
 
 @Autowired
 public Employee(EmployeeService employeeService) {
   this.employeeService = employeeService;
 }
 :
 :
}
Run Code Online (Sandbox Code Playgroud)

据我所知,现在 Spring 非常先进,Spring 构造函数/setter DI 即使没有@Autowired如下所示也能工作

@Service
public class Employee {

 private EmployeeService employeeService;

 public Employee(EmployeeService employeeService) {
   this.employeeService = employeeService;
 }
 :
 :
}
Run Code Online (Sandbox Code Playgroud)

想知道人们是否有任何理由使用@Autowired注释来注释构造函数以注入依赖项。

有人可以帮我解决这个问题吗

dun*_*nni 8

没有技术原因需要这样做(除非您有多个构造函数等)。最可能的原因是,当Spring不支持构造函数的自动检测并且仍然有必要时,人们已经学会了使用它,俗话说,旧习难改。另外,如果你搜索任何示例,你仍然会发现很多教程,其中使用了注释,所以这是另一个原因。@Repository这与Spring Data 接口上的注释相同。该注释在那里完全是错误的,但是这个网站上有很多问题,人们在代码中添加了这个注释。