问题

在学习了SpringIOC的DI依赖注入后,我们可以根据对象之间的依赖关系的责任链,让Spring容器对象帮我们创建有一个组装好的对象,比如A中有B,B 中有C,C中有D.将A,B ,C,D都创建为Bean对象,然后使用ref属性告诉Spring对象之间的依赖关系的组装规则,假如依赖责任链特别长,使用ref注入就会很麻烦.怎么办?

解决

不要声明ref属性来指明依赖关系的注入,只需要告诉Spring容器对象依赖关 系的注入规则,Spring容器对象自动根据规则完成依赖关系的注入

一、byName:根据bean的id属性和类的属性名一致的规则

<bean id="student" class="com.pojo.Student" autowire="byName"> //autowire:byName
    <property name="name" value="张三"></property>
</bean>

<bean id="tea" class="com.pojo.Teacher"> //id和com.pojo.Student类中的属性名一致
    <property name="name" value="黎老师"></property>
</bean>

二、byType:根据bean的class属性和类的属性类型一致的规则

<bean id="student" class="com.pojo.Student" autowire="byType"> //autowire:byType
    <property name="name" value="张三"></property>
</bean>
<bean id="tea4" class="com.pojo.Teacher"> //id可以和类中的属性名不一致,但是class需要和类中属性的类型一致
    <property name="name" value="黎老师"></property>
</bean>

注意:

使用byType规则的自动注入需要保证需要注入的属性在配置文件中只存在一个

三、constructor:根据构造器形参的类型和bean的类型一致的规则

一般不使用

四、使用默认规则

<?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.xsd"
        default-autowire="byType"> //在配置文件的头部进行设置,声明该配置文件中所有的自动注入方式