@Autowired注解是实现依赖注入的一种相对较新的样式。 它允许您将其他豆注入另一个所需的豆中。 与@Required的注解类似,@Autowired注解可用于在 setter 方法以及构造函数和属性上“自动装配” bean。

setter 方法上的@Autowired
请注意,在 setter 方法上使用@Autowired注解时,它会自动摆脱 XML 配置文件中的<property>元素。 相反,当 Spring 发现使用@Autowired注释的 setter 方法时,它将对该特定方法执行按类型“自动装配”。
让我们看看@Autowired在实践中。 更具体地说,在设置方法上使用@Autowired。
ExampleService.java
public class ExampleService {private Employee employee;@Autowiredpublic void setEmployee(Employee emp) {// setting the employeeemployee = emp;}}
分解
上面的示例中没有什么花哨的。 我们只有一个名为ExampleService的服务类,该类具有一个Employee类型的实例变量,并且有一个名为setEmployee(Employee emp)的设置方法,该方法仅用于设置雇员为参数给出的任何东西。
感谢@Autowired注解,在实例化ExampleService时,将Employee的实例作为该方法的参数注入。
构造函数上的@Autowired注释
public class ExampleService {private Employee employee;@Autowiredpublic ExampleService(Employee employee) {this.employee = employee;}@Autowiredpublic void setEmployee(Employee emp) {// setting the employeeemployee = emp;}}
再次感谢@Autowired注释,当实例化ExampleService时,将Employee的实例作为构造函数的参数注入。
属性上的@Autowired注释
自动装配属性节省了我们的时间和代码行。 怎么样? 好吧,当我们在属性上使用该注解时,这些属性不再需要 getter 和 setter。 酷吧?
public class ExampleService {@Autowiredprivate Employee employee;@Autowiredpublic ExampleService(Employee employee) {this.employee = employee;}@Autowiredpublic void setEmployee(Employee emp) {// setting the employeeemployee = emp;}}
在上面的代码片段中,我们自动连接了名为employee的属性。 因此,它不再需要 setter 和 getter 方法。employee在创建ExampleService时被 Spring 注入。
可选依赖项
@Autowired也可以是可选的。 像这样:
public class ExampleService {@Autowired(required = false)private Employee employee;@Autowiredpublic ExampleService(Employee employee) {this.employee = employee;}@Autowiredpublic void setEmployee(Employee emp) {// setting the employeeemployee = emp;}}
required = false使其不是必需的依赖项。
我们需要可选依赖项的原因是因为 Spring 希望在构造依赖项 bean 时@Autowired的依赖项可用。 否则,将引发错误。 由于required = false,我们可以解决此问题。
总结
通过使用@Autowired注解,我们节省了几行代码,还节省了一些时间,因为我们不需要指定属性和构造函数参数。
