Spring自动装配模式三:byType的解析

Spring自动装配模式三:byType的解析

如果容器中存在一个与指定属性类型相同的bean,那么将与该属性自动装配。如果存在多个该类型的bean,那么将会抛出异常,并指出不能使用byType方式进行自动装配。若没有找到相匹配的bean,则什么事都不发生,属性也不会被设置。如果你不希望这样,那么可以通过设置dependency-check="objects"Spring抛出异常。

配置文件如下:

        <bean id="homeAddressServiceImpl" class="cn.csdn.service.HomeAddressServiceImpl"

       scope="singleton">

       <property name="address">

           <value>北京海淀上地软件园</value>

       </property>

    </bean>

<bean id="empServiceImpl" class="cn.csdn.service.EmpServiceImpl"

       scope="singleton" autowire="byType" />

 

cn.csdn.service.HomeAddressServiceImpl

public class HomeAddressServiceImpl extends AddressServiceImpl {

   

    private String address;

   

    public void setAddress(String address){

       this.address=address;

    }

   

   

   

    public HomeAddressServiceImpl() {

       super();

    }

 

 

 

    public HomeAddressServiceImpl(String address){

       this.address=address;

    }

 

}

 

cn.csdn.service.EmpServiceImpl 代码

package cn.csdn.service;

public class EmpServiceImpl {

 

    private HomeAddressServiceImpl homeAddressServiceImpl;

 

    public void setHomeAddressServiceImpl(

           HomeAddressServiceImpl homeAddressServiceImpl) {

       this.homeAddressServiceImpl = homeAddressServiceImpl;

    }

 

}

 

注意:类型匹配指的是class 中的Employee匹配

    在配置文件中 使用byType类型时,相同类型的实例只能存在一个。 如果存在多个该类型的bean,那么将会抛出异常:       org.springframework.beans.factory.UnsatisfiedDependencyException

原因是:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [spr.bean.Employee] is defined   并指出不能使用byType方式进行自动装配。

bytype: 类型相同可以匹配

      父类与子类匹配的方式是:子类自动装载成父类的对象。

      接口与实现类:实现类的对象可以自动装载到接口的对象。否则会出现空指针异常。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值