自动装配就是我们在不使用<constructor-arg>和<property>注入数据的情况下,Spring容器自动装配相互协作的bean 的关系
这种方式可以有效减少配置文件的体积
缺点:
在同一个项目中使用效果好,但是可能会混乱,可读性差可以重写<constructor-arg>和 <property> 设置依赖关系但是可读性很差;
不能自动装配所谓的简单类型包括基本类型,字符串和类;
尽管如此不推荐使用自动装配,但是我们仍然需要了解一下,
byName
- 设置 autowire属性为byName
- 基本类型无法这么做,一般是指引用类型;
- 当我们这么设置时,Spring 容器会扫描xml配置文件,根据java bean中那个引用类型的参数名称类查找xml配置中是否有符合的名字相同bean配置,找到就注入到该参数;
<bean class="com.ldl.test.AutowireBean.Student" id="student" autowire="byName">
<property name="age" value="18"/>
<property name="name" value="ldl"/>
</bean>
<bean class="com.ldl.test.AutowireBean.Talent" name="talent">
<property name="talentss">
<list>
<value>Spring</value>
<value>SpringMVC</value>
<value>Spring Clound</value>
</list>
</property>
</bean>
byType
- 根据javaBean 中参数的类型 在xml配置文件中查找,不受名称的现在;
- 基本类型不能自动注入
- 无论是通过什么方式自动装配,我们都可以手动设置,即使 property或者<constructor-arg>
<bean class="com.ldl.test.AutowireBean.Student" id="student" autowire="byType">
<property name="age" value="18"/>
<property name="name" value="ldl"/>
</bean>
<!-- <bean class="com.ldl.test.AutowireBean.Talent" name="talent">
<property name="talentss">
<list>
<value>Spring</value>
<value>SpringMVC</value>
<value>Spring Clound</value>
</list>
</property>
</bean>-->
<bean class="com.ldl.test.AutowireBean.Talent" id="talentss">
<property name="talentss">
<list>
<value>公猪</value>
<value>母猪</value>
<value>老磕猪</value>
</list>
</property>
</bean>
构造函数自动装配
- autowire属性设置为constructor
- 根据javaBean的构造函数去匹配xml中的一个bean,尝试去寻找匹配项;也不受名称限制
<bean class="com.ldl.test.AutowireBean.Student" id="student" autowire="constructor">
<!--<property name="age" value="18"/>-->
<!--<property name="name" value="ldl"/>-->
<constructor-arg name="name" value="ldl"/>
<constructor-arg name="age" value="18"/>
</bean>
<!-- <bean class="com.ldl.test.AutowireBean.Talent" name="talent">
<property name="talentss">
<list>
<value>Spring</value>
<value>SpringMVC</value>
<value>Spring Clound</value>
</list>
</property>
</bean>-->
<bean class="com.ldl.test.AutowireBean.Talent" id="talentsszz">
<property name="talentss">
<list>
<value>公猪</value>
<value>母猪</value>
<value>老磕猪</value>
</list>
</property>
</bean>