XML配置里的bean自动装配
在非自动装配下,我们的xml配置文件是这样的,这里有三个bean,car(车),addres(地址),person(人)。person引用钱两个bean。
<bean id="car" class="jjh.test.autowire.Car" p:band="baoma" p:price="300000"></bean>
<bean id="address" class="jjh.test.autowire.Address" p:city="changsha" p:stress="YUHUAQU"></bean>
<bean id="person" class="jjh.test.autowire.Person" p:name="jjh" p:address-ref="address" p:car-ref="car"></bean>
测试结果
自动装配有两种形式,ByType和ByName。
1.ByName
我将person的bean改成了通过名字自动装配,可以通过autowire属性指定自动装配的模式,byName根据bean的setter风格的属性名进行自动装配,若有匹配的则自动进行装配,若无匹配的则不装配
<bean id="person" class="jjh.test.autowire.Person" p:name="jjh" autowire="byName"></bean>
结果同上面一致。
缺点:若有多个同类型的bean系统只会自动装配按上下顺序的第一个bean
2.ByType
ByType根据类型进行匹配,若在xml文件下有同类型的bean则自动匹配
<bean id="person" class="jjh.test.autowire.Person" p:name="jjh" autowire="byType"></bean>
缺点:当同类型的bean有多个时,系统不知道要匹配哪个
我这里添加的一个类型的两个bean
报错