参考自:https://www.cnblogs.com/ViviChan/p/4981539.html
autowire属性的作用
- 当在一个bean的属性里注入另外一个bean,要使用< property>标签+ref引用的形式。
- 但是在大型项目,一个被引用的bean的id改变了,那么需要修改所有引用了它的id
- 如果使用了bean 的 autowire 属性,那么引用bean的ref就都不需要修改了。
<!-- 使用引用的方式 -->
<bean id="cat" class="com.wei.pojo.Cat"></bean>
<bean id="user" class="com.wei.pojo.User" autowire="byType">
<property name="cat" ref="cat" />
</bean>
<!-- 使用autowire的方式 不仅更加简洁,而且更加简单。 -->
<bean id="user" class="com.wei.pojo.User" autowire="byType"></bean>
autowire属性的几种用法
模式 | 说明 |
---|---|
no | (默认)不采用autowire机制。当我们需要使用依赖注入,只能用 ref |
byName | 通过属性的名称自动装配(注入)。Spring会在容器中查找名称与bean属性名称一致的bean,并自动注入到bean属性中。当然bean的属性需要有setter方法。例如:bean A有个属性master,master的setter方法就是setMaster,A设置了autowire=“byName”,那么Spring就会在容器中查找名为master的bean通过setMaster方法注入到A中。 |
byType | 通过类型自动装配(注入)。Spring会在容器中查找类(Class)与bean属性类一致的bean,并自动注入到bean属性中,如果容器中包含多个这个类型的bean,Spring将抛出异常。如果没有找到这个类型的bean,那么注入动作将不会执行。 |
constructor | 类似于byType,但是是通过构造函数的参数类型来匹配。假设bean A有构造函数A(B b, C c),那么Spring会在容器中查找类型为B和C的bean通过构造函数A(B b, C c)注入到A中。与byType一样,如果存在多个bean类型为B或者C,则会抛出异常。但时与byType不同的是,如果在容器中找不到匹配的类的bean,将抛出异常,因为Spring无法调用构造函数实例化这个bean。 |
default | 采用父级标签的配置。(即beans的default-autowire属性) |
no
byName
- 通过属性的名称自动装配(注入)。Spring会在容器中查找名称与bean属性名称一致的bean,并自动注入到bean属性中。
- 当然bean的属性需要有setter方法。要么手写、要么lombok,才有set方法,不然会报空指针异常。
@Data
public class User {
private Cat cat;
public Cat getCat() {
return cat;
}
/**
* setter()注入
*/
public void setCat(Cat cat) {
this.cat = cat;
}
}
- 当使用byName属性时候,只需要id或者name 属性 一个为 bean所对应的名称即可注入。
<bean id="user" class="com.wei.pojo.User" autowire="byName"></bean>
<bean id="catXXX" name="cat" class="com.wei.pojo.Cat"></bean>
byType
- 通过类型自动装配(注入)。Spring会在容器中查找类(Class)与bean属性类一致的bean,并自动注入到bean属性中。
<bean id="user" class="com.wei.pojo.User" autowire="byType"></bean>
<bean id="cat" name="cat2" class="com.wei.pojo.Cat" ></bean>
-
bean的属性需要有setter方法。与byName一样。如果缺少,则报空指针。
-
如果容器中包含多个这个类型的bean,Spring将抛出异常。
显而易见,在xml配置文件之中已经出错。
- 运行之后出现的错误:
org.springframework.beans.factory.parsing.BeanDefinitionParsingException:
Configuration problem: Bean name 'cat2' is already used in this <beans> element
- 如果没有找到这个类型的bean,那么注入动作将不会执行。(没有配置 bean - Cat 或 找不到)
java.lang.NullPointerException
constructor
- 通过构造函数的参数类型来匹配。
@Data
public class User {
private Cat cat;
public User(Cat cat){
this.cat = cat;
}
}
- 如果缺少该构造函数则报空指针异常。
default
- 在< beans/>标签中指定default-autowire属性,那么对于子标签如果没有单独的设置autowire属性,那么将采用父标签的default-autowire属性的模式,如果单独设置了autowire属性,则采用自己的模式。
- 采用父级标签(即beans的default-autowire属性)的配置。
补充
- 其中byType和constructor模式也支持数组和强类型集合(即指定了集合元素类型)
- Map的key必须是String类型,Spring会根据value的类型去匹配。
- 虽然autowrie给我们带来配置的便利性,但是也有缺点,比如会导致bean的关系没那么显而易见,所以用autowire还是ref还是需要根据项目来决定。