/**
*
* 通过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[]中。