1.autowire常用的两种方式
1)byName:按照名字自动匹配
2) byType:按照类型自动匹配
2.测试用例
1)配置文件:(按名字装配)
<?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.5.xsd">
<bean id="impl" class="org.sh.spring.impl.IUserDAOImpl">
<property name="daoId" value="1"></property>
</bean>
<bean id="u2" class="org.sh.spring.impl.IUserDAOImpl">
<property name="daoId" value="2"></property>
</bean>
<bean id="userservice" class="org.sh.spring.Services.UserServices" scope="prototype" init-method="init" destroy-method="destory" autowire="byName">
</bean>
<!-- more bean definitions go here -->
</beans>
注意UserService.java 中有一个
IUserDAOImpl.java 的属性 为impl 配置文件中有两个IUSerDAOImpl的bean 如果按Name自动装配那么将会使用的是第一个bean,即daoId的值为1
测试:
IUserDAOImpl.java 复写toString()方法
public String toString() {
return this.daoId+"";
}
Test.java
@Test
public void testSave() {
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
UserServices ud = (UserServices)ctx.getBean("userservice");
System.out.println(ud.getImpl());
}
测试结果:
daoID=1 测试成功
2)按类型装配
<bean id="userservice" class="org.sh.spring.Services.UserServices" scope="prototype" init-method="init" destroy-method="destory" autowire="byType">
如果bean.xml中有两个符合条件的bean那么将会报错
其余不变测试结果为 daoId = 2
autowire 也可以放在beans标签中 表明配置文件中所有的装配方式都用这个 default-autowire=""