Spring由类型(Type)自动装配

在Spring中,“类型自动装配”的意思是如果一个bean的数据类型与其它bean属性的数据类型相同,将自动兼容装配它。
例如,一个“persion” bean 公开以“ability”类数据类型作为属性,Spring会找到ability类相同的数据类型,并自动装配它的Bean。如果没有匹配找到,它什么也不做。
可以通过自动装配 autowire="byType"象下面这样:
<!-- person has a property type of class "ability" -->
	<bean id="person" class="com.zyiz.netmon.Person" autowire="byType" />
		
	<bean id="invisible" class="com.zyiz.netmon.Ability" >
		<property name="skill" value="Invisible" />
	</bean>
看下面由Spring按类型自动装配的完整例子。

1. Beans

两个Bean,person 和 ability.
package com.zyiz.netmon;
 
public class Person 
{
	private Ability ability;
	//...
}
package com.zyiz.netmon;
 
public class Ability 
{
	private String skill;
	//...
}

2. Spring Wiring

通常情况下,明确地装配 bean:
<bean id="person" class="com.zyiz.netmon.Person">
		<property name="ability" ref="invisible" />
	</bean>
	
	<bean id="invisible" class="com.zyiz.netmon.Ability" >
		<property name="skill" value="Invisible" />
	</bean>

输出

Person [ability=Ability [skill=Invisible]]
随着自动装配按类型启用后,可以保留ability属性未设置。Spring会发现相同的数据类型并自动装配它。
<bean id="person" class="com.zyiz.netmon.Person" autowire="byType" />
	
	<bean id="invisible" class="com.zyiz.netmon.Ability" >
		<property name="skill" value="Invisible" />
	</bean>

输出

Person [ability=Ability [skill=Invisible]]
如果你有两个Bean,都是类“ability”相同的数据类型?
<bean id="person" class="com.zyiz.netmon.Person" autowire="byType" />
	
	<bean id="steal" class="com.zyiz.netmon.Ability" >
		<property name="skill" value="Steal" />
	</bean>
	
	<bean id="invisible" class="com.zyiz.netmon.Ability" >
		<property name="skill" value="Invisible" />
	</bean>

输出

Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: 
...
No unique bean of type [com.zyiz.netmon.Ability] is defined: 
expected single matching bean but found 2: [steal, invisible]; nested exception is 
org.springframework.beans.factory.NoSuchBeanDefinitionException: 
No unique bean of type [com.zyiz.netmon.Ability] is defined: 
expected single matching bean but found 2: [steal, invisible]
在这种情况下,它会打出 UnsatisfiedDependencyException 的错误消息。

在类型的自动装配模式,就必须确保只有Bean 只有一个唯一的数据类型声明。

下载源代码 – http://pan.baidu.com/s/1gdQFszD

上一篇:Spring自动装配Beans

下一篇:Spring由名称(Name)自动装配

关注微信小程序
程序员编程王-随时随地学编程

扫描二维码
程序员编程王

扫一扫关注最新编程教程