根据名称或类型自动装配(为了减少配置量)
PS:开发阶段不建议使用自动装配,以为它会使得类与类之间的依赖关系变得不明确!
加入有一个bean Bean2.java,它依赖于Bean3 ,Bean4 ,Bean5,代码如下:
public class Bean2 {private Bean3 bean3;private Bean4 bean4;private Bean5 bean5;public Bean3 getBean3() {return bean3;}public void setBean3(Bean3 bean3) {this.bean3 = bean3;}public Bean4 getBean4() {return bean4;}public void setBean4(Bean4 bean4) {this.bean4 = bean4;}public Bean5 getBean5() {return bean5;}public void setBean5(Bean5 bean5) {this.bean5 = bean5;}}spring配置文件如下:
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd" default-autowire="byName"//注意这里,加上需要的装配样式,如果是根据类型自动装配就是byType ><!-- 原来是这样写的<bean id="bean2" ref="bean3"/><property name="bean4" ref="bean4"/><property name="bean5" ref="bean5"/></bean> --><!--现在只需要这样写--><bean id="bean2" class="com.bjsxt.spring.Bean5"/></beans>
注意:
如果是根据名称自动装配(byName),那么bean2里的属性bean3,bean4,bean5就要和配置文件中的id一致,否则spring会找不到相应的名称而报错。
如果是根据类型自动装配(byType),则属性名和id号可以不一致,因为是以类型自动装配的,spring会自动根据‘类型’自动装配。