Spring学习笔记(三)

1、依赖注入第二种方式(构造注入):在构造实例的时候,已经为其完成了依赖关系的初始化。

2、修改Chinese类:

package com.sxit.service.impl;

import com.sxit.service.FishingRod;
import com.sxit.service.Person;

public class Chinese implements Person {

	private FishingRod fishingRod;	//鱼竿
	
	//带参数的构造器
	public Chinese (FishingRod fishingRod){
		this.fishingRod = fishingRod;
	}
	
	public void useFishingRod() {
		fishingRod.fishing();	//开始钓鱼
	}

	public FishingRod getFishingRod() {
		return fishingRod;
	}

	public void setFishingRod(FishingRod fishingRod) {
		this.fishingRod = fishingRod;
	}
}

 3、修改Bean3.xml为:

<?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:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:oscache="http://www.springmodules.org/schema/oscache"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springmodules.org/schema/oscache http://www.springmodules.org/schema/cache/springmodules-oscache.xsd">

	<bean id="fishingRod" class="com.sxit.service.impl.FishingRod" />

	<bean id="Chinese" class="com.sxit.service.impl.Chinese">
		<constructor-arg ref="fishingRod"/>
	</bean>

</beans>

 4、测试类Test3:

package com.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.sxit.service.impl.Chinese;

public class Test3 {

	public static void main(String[] args) {
		
		ApplicationContext apc = new ClassPathXmlApplicationContext("Bean3.xml");
		Chinese chinese = apc.getBean("Chinese", Chinese.class);
		chinese.useFishingRod();
	}
}

 5、打印信息:

哈哈,Spring开始给我钓鱼啦!

 6、总结:

1)、构造器注入是通过<constructor-arg ref=""/>标签来指定构造器的参数。
2)、还可以通过<constructor-arg index="0" ref="fishingRod"/>来设置参数,index为0,即构造器第1个参数。

 7、两种注入方式的比较:

1)、设值注入是先实例化对象,然后根据相应的setter方法来注入属性值,构造注入是根据默认的构造器实例化的同时,对象之间的依赖关系就已经注入完成。
2)、设置注入与传统JavaBean写法类似,通过setter方法来设定依赖关系显得更加直观和自然。而如果对于参数值比较多,依赖关系复杂的时候,通过构造注入的话就显得非常的臃肿及不易阅读,而且实例化的时候需要把所有依赖的对象全部实例化一遍,会导致性能下降(有些参数可选的情况下)。
3)、构造注入的好处有:可以在构造器中决定依赖关系注入的顺序,比如很多组件需要依赖于DataSource的注入,采用构造注入就可以方便的决定注入顺序。

猜你喜欢

转载自luan.iteye.com/blog/1717125