spring学习笔记(6)--自动装配autowire

来源:互联网 发布:高性能网络编程 二 编辑:程序博客网 时间:2024/06/05 19:32

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

@Testpublic 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=""

0 0
原创粉丝点击