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