自动装配举例:byType

/**
 * 
 * 通过byType自动装配进行注入
 * 
 * collaboratorBean 单个bean,在配置元数据中不能有多个同类型的bean,否则会出错
 * set 集合,将多个同类性的bean注入这个集合(array)中
 */

public class Dependent {

    private Collaborator collaboratorBean;
    private SetElement[] set ;

    public void setCollaboratorBean(Collaborator collaboratorBean) {
        this.collaboratorBean = collaboratorBean;
    }
    public void setSet(SetElement[] set) {
        this.set = set;
    }
    @Override
    public String toString() {
        return "Dependent [collaboratorBean=" + collaboratorBean + ",\n\tset=" + Arrays.toString(set) + "\n]";
    }
}

public class Collaborator {
    private String info;

    public void setInfo(String info) {
        this.info = info;
    }

    public String toString() {
        return "Collaborator [info=" + info + "]";
    }
}

public class SetElement {
    private String info;

    public void setInfo(String info) {
        this.info = info;
    }

    public String toString() {
        return "SetElement [info=" + info + "]";
    }
}

配置元数据:

<!-- 将单个的bean注入 -->
<bean id="one" class="SpringTest.autoWire.byType.Collaborator">
    <property name="info" value="This is collaboratorBean"/>
</bean>

<!-- 下面的3个bean被注入到集合中 -->
<bean id="element1" class="SpringTest.autoWire.byType.SetElement">
    <property name="info" value="element1"/>
</bean>

<bean id="element2" class="SpringTest.autoWire.byType.SetElement">
    <property name="info" value="element2"/>
</bean>

<bean id="element3" class="SpringTest.autoWire.byType.SetElement">
    <property name="info" value="element3"/>
</bean>

输出结果:System.out.println(context.getBean("dependent"));

  

分析

byType注入可以给集合(或array)注入依赖,因此,对于byType自动装配,有以下两种情况:

1.对非集合(或array)依赖的自动装配

对于这种情况,就上面的例子,属性collaboratorBean就是一个非集合的依赖,给它进行依赖注入时,Spring查找与它类型相同的bean,然后通过setter注入。

注:Spring查找的时候,不能出现二义性。如果有两个同类型的bean都符合要求,则会出错。

如果给上面的例子再配置一个bean:

<bean id="two" class="SpringTest.autoWire.byType.Collaborator">
    <property name="info" value="This is collaboratorBean"/>
</bean>

对于属性collaboratorBean来说,有两个bean和它匹配,所以就会出现二义性,Spring就会抛出异常。

2.对集合依赖的自动装配

如果是一个集合类型的依赖,Spring会把所有类型与集合元素类型匹配的bean注入到集合中。

就像上面的三个SetElment类型的bean,都被注入到SetElement[]中。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值