转:spring的自动装配(default-autowire="byName")
? <property name="bean4">
?? <ref bean="bean4"/>
? </property>?
? <property name="bean5" ref="bean5"/>
?</bean>
很明显,下面的几个属性设置是很繁琐的..我们假设使用自动装配.我们只需要这样
<bean id="bean2" />
里面的装配都不用写.
当然,自动装配必须满足两点
(1)bean2.java里面的属性名字必须和applicationContext.xml里面对应的bean id的名字相同..也就是
?private Bean3 bean3;? 这个bean3(其实对应的是get,set方法)必须和
<bean id="bean3" value="Tom" />
? <property name="password" value="123" />
?</bean>? 这个bean3相同.否则不能自动装配
(2)在申明里配置一个属性.default-autowire="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"
?xsi:schemaLocation="http://www.springframework.org/schema/beans?
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"
?default-autowire="byName">
?<bean id="abstractBean" abstract="true">
? <property name="id">
?? <value>1000</value>
? </property>
? <property name="name" value="java" />
?</bean>
?<bean id="bean2" />
?<bean id="bean3" value="Tom" />
? <property name="password" value="123" />
?</bean>
?<bean id="bean4" parent="abstractBean" />
?<bean id="bean5" value="20" />
?</bean>
default-autowire="x"
x有4个选择:byName,byType,constructor和autodetect
1. byName:
Service.java
public class Service
{
??? Source source;
??? public void setSource(Source source)
??? {
??????? this.source = source;
??? }
}
applicationContext.xml
<beans
?? ...
?? default-autowire="byName">
??? <bean id="source" scope="prototype"/>
??? <bean id="service" scope="prototype">
??? </bean>
</beans>
cn.hh.spring.DBCPSource实现了Source接口
xml中并没有给 bean service配Source属性,但在beans中设置了autowire="byName",这样配置文件会自
动根据 cn.hh.spring.Service 中的setSource找bean id="Source"的bean ,然后自动配上去,如果没找
到就不装配。
注意:byName的name是java中setXxxx 的Xxxx, 和上面设置的Source source中source拼写毫无关系,完
全可以是
public class Service
{
??? Source source1;
??? public void setSource(Source source1)
??? {
??????? this.source1 = source1;
??? }
}
2. byType:
Service.java同上
applicationContext.xml
<beans
?? ...
?? default-autowire="byType">
??? <bean id="dbcpSource" scope="prototype"/>
??? <bean id="service" scope="prototype">
??? </bean>
</beans>
同样没有配置setSource,autowire改成 "byType",配置文件会找实现了Source接口的bean,这里?
cn.hh.spring.DBCPSource 实现了Source接口,所以自动装配,如果没找到则不装配。
如果同个配制文件中两个bean实现了Source接口,则报错。
这里的 Type是指setSource(Source source)中参数的类型。
3. constructor:
试图在容器中寻找与需要自动装配的bean的构造函数参数一致的一个或多个bean,如果没找到则抛出异常
。
4. autodetect:
首先尝试使用constructor来自动装配,然后再使用byType方式。