SpringIOC容器-xml配置bean-xml中bean的自动装配

时间:2020-04-17
本文章向大家介绍SpringIOC容器-xml配置bean-xml中bean的自动装配,主要包括SpringIOC容器-xml配置bean-xml中bean的自动装配使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

前面我们都是当bean中要引用另一个bean的时候,我们都是采用了ref去指定确切的bean的id

那么,Spring为我们提供了自动装配的功能,只需要在bean上添加一个属性即可

autowire属性,这个属性有2个值:byName和byType

当值为byName的时候,bean中属性(引用类型)在IOC容器中寻找用来装配的bean的时候,查找是根据属性名去找bean的id,找不到就是null

当值为byType的时候,bean中属性(引用类型)在IOC容器中寻找用来装配的bean的时候,查找是根据类去找bean的,找不到就是null,找到2个就抛异常

示例:

<bean id="car" class="com.llf.bean.Car">
    <property name="brand" value="宝马"></property>
    <property name="price" value="2000000"></property>
    <property name="speed" value="300.00"></property>
</bean>

<bean id="person" class="com.llf.bean.Person" autowire="byName">
    <property name="name" value="llf"></property>
    <property name="age" value="22"></property>
</bean>
<bean id="person1" class="com.llf.bean.Person" autowire="byType">
    <property name="name" value="fll"></property>
    <property name="age" value="22"></property>
</bean>

在 Bean 配置文件里设置 autowire 属性进行自动装配将会装配 Bean 的所有属性. 然而, 若只希望装配个别属性时, autowire 属性就不够灵活了.
autowire 属性要么根据类型自动装配, 要么根据名称自动装配, 不能两者兼而有之.
一般情况下,在实际的项目中很少使用自动装配功能,因为和自动装配功能所带来的好处比起来,明确清晰的配置文档更有说服力一些

 

原文地址:https://www.cnblogs.com/linglongfang/p/12721681.html