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

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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值