- @Autowired 是一个注释,它可以对类成员变量、方法及构造函数进行标注,让 spring 完成 bean 自动装配的工作。
- @Autowired 默认是按照类去匹配,当多个bean类型的对象时,配合 @Qualifier 指定按照名称去装配 bean。
- 当不能确定 Spring 容器中一定拥有某个类的 Bean 时,可以在需要自动注入该类 Bean 的地方可以使用
@Autowired(required = false),这等于告诉 Spring:在找不到匹配 Bean 时也不报错。
使用 @Autowired 注解
Spring 2.5 引入了 @Autowired 注释,它可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作。来看一下使用@Autowired 进行成员变量自动注入的代码:
public class Boss {
@Autowired
private Car car;`在这里插入代码片`
@Autowired
private Office office;
…
}
Spring 通过一个 BeanPostProcessor 对 @Autowired 进行解析,所以要让@Autowired 起作用必须事先在 Spring 容器中声明 AutowiredAnnotationBeanPostProcessor Bean。
让 @Autowired 注释工作起来
利用xml配置或者@Component注解都可以注册成一个bean对象
这里用xml配置如下:
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<!-- 该 BeanPostProcessor 将自动起作用,对标注 @Autowired 的 Bean 进行自动注入 -->
<bean class="org.springframework.beans.factory.annotation.
AutowiredAnnotationBeanPostProcessor"/>
<!-- 移除 boss Bean 的属性注入配置的信息 -->
<bean id="boss" class="com.baobaotao.Boss"/>
<bean id="office" class="com.baobaotao.Office">
<property name="officeNo" value="001"/>
</bean>
<bean id="car" class="com.baobaotao.Car" scope="singleton">
<property name="brand" value=" 红旗 CA72"/>
<property name="price" value="2000"/>
</bean>
</beans>
这样,当 Spring 容器启动时,AutowiredAnnotationBeanPostProcessor 将扫描 Spring 容器中所有 Bean,当发现 Bean 中拥有@Autowired 注释时就找到和其匹配(默认按类型匹配)的 Bean,并注入到对应的地方中去。
按照上面的配置,Spring 将直接采用 Java 反射机制对 Boss 中的 car 和 office 这两个私有成员变量进行自动注入。所以对成员变量使用@Autowired 后,您大可将它们的 setter 方法(setCar() 和 setOffice())从 Boss 中删除。
当然,您也可以通过 @Autowired 对方法或构造函数进行标注,来看下面的代码:
将 @Autowired 注解标注在 Setter 方法上
public class Boss {
private Car car;
private Office office;
@Autowired
public void setCar(Car car) {
this.car = car;
}
@Autowired
public void setOffice(Office office) {
this.office = office;
}
…
}
这时,@Autowired 将查找被标注的方法的入参类型的 Bean,并调用方法自动注入这些 Bean。而下面的使用方法则对构造函数进行标注:
将 @Autowired 注解标注在构造函数上
public class Boss {
private Car car;
private Office office;
@Autowired
public Boss(Car car ,Office office){
this.car = car;
this.office = office ;
}
…
}
由于 Boss() 构造函数有两个入参,分别是 car 和 office,@Autowired 将分别寻找和它们类型匹配的 Bean,将它们作为Boss(Car car ,Office office) 的入参来创建 Boss Bean。
当候选 Bean 数目不为 1 时的应对方法:
- 当为0时可以用@Autowired(required = false)解决
- 当bean对象大于1时用@Autowired和@Qualifier结合使用
与依赖注入有关的注解还有@Resource,有兴趣可以查找@Autowired,@Qualifier和@Resource区别与联系