---
title: "Spring3核心技术之DI依赖注入"
author: "一日一博"
date: "2012-08-29T15:12:40Z"
tags: []
categories: ["编程语言"]
slug: "spring3-di"
draft: false
lastmod: "2012-09-04T22:15:07Z"
id: 1666054
url: "https://chouyi.iteye.com/blog/1666054"
---

IoC的一个重点是在系统运行中，动态的向某个对象提供它所需要的其他对象。这一点是通过<span style="color:red">DI（Dependency Injection，依赖注入）</span>来实现的。顾名思义，依赖注入就是Spring管理下的Bean需要依赖Spring容器来帮他注入属性。
这篇博客对IOC和DI有比较好的解释：<http://jinnianshilongnian.iteye.com/blog/1471944>

<span style="color:blue">Spring IoC容器的依赖有两层含义：Bean依赖容器和容器注入Bean的依赖资源。</span>
● Bean依赖容器：也就是说Bean要依赖于容器，这里的依赖是指容器负责创建Bean并管理Bean的生命周期，正是由于由容器来控制创建Bean并注入依赖，也就是控制权被反转了，这也正是IoC名字的由来，此处的有依赖是指Bean和容器之间的依赖关系。
● 容器注入Bean的依赖资源：容器负责注入Bean的依赖资源，依赖资源可以是Bean、外部文件、常量数据等，在Java中都反映为对象，并且由容器负责组装Bean之间的依赖关系，此处的依赖是指Bean之间的依赖关系，可以认为是传统类与类之间的“关联”、“聚合”、“组合”关系。

<span style="color:red">从以上我们可以看出，其实依赖注入只是一种装配对象的手段，设计的类结构才是基础，</span>如果设计的类结构不支持依赖注入，Spring IoC容器也注入不了任何东西，从而从根本上说“如何设计好类结构才是关键，依赖注入只是一种装配对象手段”。
<span style="color:blue">Spring注入依赖资源主要有以下两种常用实现方式</span>
● 构造器注入：就是容器实例化Bean时注入那些依赖，通过在在Bean定义中指定构造器参数进行注入依赖，包括实例工厂方法参数注入依赖，但静态工厂方法参数不允许注入依赖（一般不推荐使用）
● setter注入：通过setter方法进行注入依赖（推荐使用）
还有静态工厂方法和实例工厂方法注入（不常用），用法请看博客：
<http://jinnianshilongnian.iteye.com/blog/1415277>

<span style="color:blue">下面这个Demo用到了Spring属性注入的两种方法（构造器注入和set方法注入）</span>
Spring不仅能注入简单类型数据，还能注入集合（Collection、无序集合Set、有序集合List）类型、数组(Array)类型、字典(Map)类型数据、Properties类型数据：

```java

public class MyBeanA implements MyBean{
	private String myName;
	private Long myAge;
	private Map<String, String> resultMap;
	private String arg1;
	private Long arg2;
	private Boolean b1;
	private Boolean b2;
	private Boolean b3;
	private Properties pros;
	private Double[] nums;

	//无参构造方法
	public MyBeanA() {}

	//构造函数 接收配置文件constructor-arg标签的参数
	//@java.beans.ConstructorProperties({"arg1", "arg2"}) 
	public MyBeanA(String arg1, Long arg2, Boolean b1, Boolean b2, Boolean b3) {
		this.arg1 = arg1;
		this.arg2 = arg2;
		this.b1= b1;
		this.b2= b2;
		this.b3= b3;
	}
	
	public void domain() {
		System.out.println("MyBeanA is executing...");
		for (int i = 0; i < nums.length; i++) {
			System.out.println(nums[i]);
		}
		System.out.println(pros.getProperty("1"));
		System.out.println(myName);
		System.out.println(myAge);
		System.out.println(arg1);
		System.out.println(arg2);
		System.out.println(b1);
		System.out.println(b2);
		System.out.println(b3);
		if (resultMap != null) {
		    System.out.println(resultMap.values());
		｝
	}
	//省略set方法
}

```


```java

public class MyBeanB implements MyBean{

	private MyBeanA beanA;

	public void setBeanA(MyBeanA myBeanA) {
		this.beanA = myBeanA;
	}
	
	public void domain() {
		System.out.println("MyBeanB is executing...");
		beanA.domain();
	}

}

```


```java

public class MyBeanC {
	private Set<MyBean> beanSet;
	private List<MyBean> beanList;
	private MyBean money;
	
	public void execute() {
		System.out.println("MyBeanC is executing...");
		System.out.println(money == null);
		for (MyBean myBean : beanList) {
			myBean.domain();
		}
	}

	//set方法
}

```

下面是配置文件applicationContext.xml的配置：
**Spring的容错处理：**注意“value”中指定的全是字符串，由Spring容器将此字符串转换成属性所需要的类型，如果转换出错，将抛出相应的异常。
Spring容器目前能对各种基本类型把配置的String参数转换为需要的类型。Spring类型转换机制对于boolean类型进行了容错处理，除了可以使用“true/false”标准的Java值进行注入，还能使用“yes/no”、“on/off”、“1/0”来代表“true/false”。

```xml

<beans ....>
	<bean id="bean_a" class="com.chou.spring.bean.MyBeanA">
		<!-- constructor-arg即通过构造函数注入,value值表示注入值,ref表示bean的id -->
		<!-- <constructor-arg  ref="beanId"/> -->
		<constructor-arg index="0" value="Hello Spring"/>
		<constructor-arg type="java.lang.Long" value="222"/>
		<!-- 注入Boolean类型数据 -->
		<constructor-arg type="java.lang.Boolean" value="1"/>
		<constructor-arg type="java.lang.Boolean" value="on"/>
		<constructor-arg type="java.lang.Boolean" value="no"/>

		<!-- property代表是通过set方法注入,value表示注入的内容,ref表示bean的id -->
		<property name="myName" value="Iverson"/>
		<property name="myAge" value="22"/>
		<property name="resultMap">
			<map key-type="java.lang.Long" value-type="java.lang.String">
				<entry key="1" value="用户或密码错"/>
				<entry key="2" value="手机号码前缀错误"/>
				<entry key="3" value="内容存在关键字错误"/>
				<entry key="4" value="超出流量"/>
			</map>
		</property>
<!-- 注入java.util.Properties类型数据，虽然指定了value-type，但是这里不起作用，键和值默认String -->
		<property name="pros">
			<props value-type="java.lang.Long">
				<prop key="1">First</prop>
				<prop key="2">Garent</prop>
				<prop key="3">Tomcat</prop>
			</props>
		</property>

<!-- 注入数组 -->
		<property name="nums">
			<array value-type="java.lang.Double">
				<value>100.11</value>
				<value>100</value>
				<value>10088</value>
			</array>
		</property>
	</bean>
	
	
	<bean id="bean_b" class="com.chou.spring.bean.MyBeanB">
		<property name="beanA" ref="bean_a"/>
	</bean>
	
	<bean id="bean_c" class="com.chou.spring.bean.MyBeanC">
		<!-- 注入Collection类型 -->
		<property name="beanSet">
			<set value-type="com.chou.spring.bean.MyBean">
				<ref bean="bean_a" />
				<ref bean="bean_b" />
			</set>
		</property>
		<property name="beanList">
			<list value-type="com.chou.spring.bean.MyBean">
				<ref bean="bean_a" />
				<ref bean="bean_b" />
			</list>
		</property>
		<!-- null值注入 -->
		<property name="money">
			<null/>
		</property>
	</bean>
	
</beans>

```


```java

String[] configs = new String[] {"applicationContext.xml"};
ApplicationContext cxt = new ClassPathXmlApplicationContext(configs);		
MyBeanC c = cxt.getBean("bean_c",MyBeanC.class);
c.execute();

```