自动装配的形式有byType、byName、no、construtor、autodetect和default(beans标签中没有,而bean标签中有该属性),共6种装配的方式。
byType:在容器中寻找一个与需要自动装配的属性类型相同的Bean,如没有找到相符Bean,该属性就没有被装配上,如果找到超过一个相符的Bean时(不能出现有继承的两个类),会抛出No unique bean of type的异常
Xml中的部分代码: <!-- 设置addressserviceimpl类 --> <bean id="addressServiceImpl" class="cn.csdn.service.AddressServiceImpl"> <property name="address"> <value>河北邢台</value> </property> </bean> <!-- 设置emp类的属性 --> <bean id="empServiceImpl" class="cn.csdn.service.EmpServiceImpl" autowire="byType"> </bean>
byName:在容器中寻找和需要自动装配的属性名相同的Bean(或ID),如果没有找到相符的Bean,该属性就没有被装配上。
Xml中的部分代码: <!-- 设置addressserviceimpl类 --> <bean id="addressServiceImpl" class="cn.csdn.service.AddressServiceImpl"> <property name="address"> <value>河北邢台</value> </property> </bean> <!-- 设置emp类的属性 --> <bean id="empServiceImpl" class="cn.csdn.service.EmpServiceImpl" autowire="byName"> </bean> <!-- 设置hour的属性 --> <bean id="hourServiceImpl" class="cn.csdn.service.HourServiceImpl"> </bean> 注意:byName和byType使用前要有一个默认的构造器,必须保证Bean能够初始化,否则的话会出现
constructor:在容器中寻找与需要自动装配的Bean的构造方法参数一致的一个或多个Bean。如存在不确定Bean或构造方法,容器会抛出org.springframework.bean.unisatisfiedBependencyException异常。通过构造器注入的,构造器中的参数是按照byType装配的
Xml中的部分代码: <!-- 设置addressserviceimpl类 --> <bean id="addressServiceImpl" class="cn.csdn.service.AddressServiceImpl"> <property name="address"> <value>河北邢台</value> </property> </bean> <!-- 设置emp类的属性 --> <bean id="empServiceImpl" class="cn.csdn.service.EmpServiceImpl2" autowire="constructor"> </bean>
no:不自动装配,必须让用户自己装配,装配时用到ref的属性。这种方式是默认的装配方式
autodetect:测试Autodetect自动装配的方法,如果没有默认的构造方法时调用seter方法,seter方法也没有的话,就不能操作了;如果有默认的构造方法,先调用默认的构造方法,如果有seter方法的话,再调用seter方法,如果没有的话,只调用默认的构造方法
Xml中的部分代码: <!-- 设置addressserviceimpl类 --> <bean id="addressServiceImpl" class="cn.csdn.service.AddressServiceImpl"> <property name="address"> <value>河北邢台</value> </property> </bean> <!-- 设置emp类的属性 --> <bean id="empServiceImpl" class="cn.csdn.service.EmpServiceImpl3" autowire="autodetect"> </bean>
default:这种装配方式只有bean标签有这个属性,相当于beans标签中的default-autowire="no"