Spring autowire自动装配 ByType和ByName

不使用自动装配前使用的是类的引用:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="car1" class="cn.Spring.Day15autowire.Car">
        <property name="carname" value="奔驰"></property>
        <property name="carcolor" value="红色"></property>
    </bean>
    <bean id="stu" class="cn.Spring.Day15autowire.Student">
        <property name="name" value="小明"></property>
        <property name="age" value="18"></property>
        <property name="car" ref="car1"></property>
    </bean>
</beans>

 

自动装配有五中模式:

no   默认的方式是不进行自动装配,通过手工设置ref 属性来进行装配bean
byName   通过参数名 自动装配,如果一个bean的name 和另外一个bean的 property 相同,就自动装配。
byType   通过参数的数据类型自动自动装配,如果一个bean的数据类型和另外一个bean的property属性的数据类型兼容,就自动装配
construct   构造方法中的参数通过byType的形式,自动装配。
default 由上级标签<beans>的default-autowire属性确定。

 使用自动装配进行注入:

使用ByType进行装配:

现在在来一个类使用ByType进行装配:

报错:因为有两个类型,ByType无法识别到。

 

 

使用ByName进行装配:

ByName依据的是:bean节点的id和类中定义的car名字相同则byName识别。

 

 

posted @ 2018-11-23 19:40  就让文谦先行  阅读(2263)  评论(1编辑  收藏  举报