【发布时间】:2021-08-29 20:00:32
【问题描述】:
我见过很多人在构造函数中使用@Autowired注解来注入如下所示的依赖项
@Service
public class Employee {
private EmployeeService employeeService;
@Autowired
public Employee(EmployeeService employeeService) {
this.employeeService = employeeService;
}
:
:
}
据我所知,现在 Spring 是如此先进,即使没有 @Autowired,Spring 构造函数/设置器 DI 也可以工作,如下所示
@Service
public class Employee {
private EmployeeService employeeService;
public Employee(EmployeeService employeeService) {
this.employeeService = employeeService;
}
:
:
}
想知道为什么人们用@Autowired注解来注解构造函数以注入依赖项。
有人可以帮我解决这个问题吗
【问题讨论】:
-
你可以有多个构造函数,如果没有
@Autowired,Spring 将不知道使用哪个构造函数 -
因为 10 个开发者中有 8 个的复制/粘贴心态。我的工作中有大约 20 名开发人员,其中大约 16 人对 Spring 的内部工作原理知之甚少。
-
@SvetlinZarev 因此,如果我们有多个构造函数,我们应该选择最有用的一个并使用
@Autowired进行注释,以便在其他地方通过 DI 注入对吧?现在我们真的需要在 Spring 上下文中拥有多个构造函数吗 -
请注意,有多个构造函数是not a good practice。
标签: java spring dependency-injection autowired