---
title: "Spring IOC&DI的应用之构造函数注入"
author: "西子湖畔的家"
date: "2015-12-09T20:36:19Z"
tags: ["DI", "IOC", "Spring框架"]
categories: ["开源软件"]
slug: "spring-ioc-di"
draft: false
lastmod: "2015-12-09T20:35:20Z"
id: 2262808
url: "https://wgfhit.iteye.com/blog/2262808"
---

前文已经介绍Spring IOC&DI主要解决了对象和对象之间的耦合问题，将每一个对象作为bean交给Spring容器来管理。本文主要总结Spring IOC&DI的具体应用，包括其xml配置文件写法、依赖注入方式、bean获取方式等。

既然是解决对象和对象之间的耦合，那根据所依赖对象的类型可以分为：

(1)基本类型对象：所依赖对象为基本类型对象。如：int、String等

(2)自定义类型：所依赖对象为其他的自定义的类类型。

(3)集合类型：所依赖对象为集合类型，如List、Set、Map、Property等

(4)null 空值

 

同时根据依赖注入的方式分为两种方式：构造器注入和setter注入（接口注入已基本被废弃）

还是以上一节的例子。

1、构造器注入方式

(1) 基本类型对象注入

假设在dao的实现类中有一个属性用来记录具体的数据库的名字，则定义如下：

 

```
package com.springframework.ioc;

public class MysqlDaoImpl implements MyDao{
	private String name;
        public MysqlDaoImpl(String name){
		this.name = name;
	}
	@Override
	public void addUser(){
		System.out.println("this is " + name + " add user...");
	}
}
```

 

需要将name通过构造函数形式注入进来。

 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"
		
		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"
			default-lazy-init="true">
			<!-- beans declare go here -->
			<bean id="mysql" class="com.springframework.ioc.MysqlDaoImpl">
				<constructor-arg  value="mysql"/>
			</bean>
			<!-- 通过含参构造器注入 -->
			<bean id = "myservice" class="com.springframework.ioc.MyService">
				<constructor-arg ref = "mysql"/>
			</bean>
</beans>
```

 如果构造函数中有两个参数呢，假设现在又加了一个id的参数。

 

```
package com.springframework.ioc;

public class MysqlDaoImpl implements MyDao{
	private String name;
        private int id;
        public MysqlDaoImpl(String name, int id){
		this.name = name;
                this.id = id;
	}
	@Override
	public void addUser(){
		System.out.println("this is " + name "id is " + id  + " add user...");
	}
}
```

这个时候可以继续以上面的方式配置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"
		
		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"
			default-lazy-init="true">
			<!-- beans declare go here -->
			<bean id="mysql" class="com.springframework.ioc.MysqlDaoImpl">
				<constructor-arg  value="mysql"/>
				<constructor-arg  value="1"/>
			</bean>
			<!-- 通过含参构造器注入 -->
			<bean id = "myservice" class="com.springframework.ioc.MyService">
				<constructor-arg ref = "mysql"/>
			</bean>
	</beans>
```

 会输出正确的结果，

```
this is mysql id is 1 add user...
```

 但是如果我调换一下顺序，变成这样：

 

```
<?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"
		
		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"
			default-lazy-init="true">
			<!-- beans declare go here -->
			<bean id="mysql" class="com.springframework.ioc.MysqlDaoImpl">

				<constructor-arg  value="1"/>
				<constructor-arg  value="mysql"/>

			</bean>
			<!-- 通过含参构造器注入 -->
			<bean id = "myservice" class="com.springframework.ioc.MyService">
				<constructor-arg ref = "mysql"/>
			</bean>
	</beans>
```

此时因为类型不匹配会报错，但是如果我两个参数都是String类型的，就会傻傻分不清楚了，所以，为了能够分清楚，一般会如下设置，指定参数的index：

 

```
<?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"
		
		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"
			default-lazy-init="true">
			<!-- beans declare go here -->
			<bean id="mysql" class="com.springframework.ioc.MysqlDaoImpl">

				<constructor-arg  index="1" value="1"/>
				<constructor-arg  index="0" value="mysql"/>

			</bean>
			<!-- 通过含参构造器注入 -->
			<bean id = "myservice" class="com.springframework.ioc.MyService">
				<constructor-arg ref = "mysql"/>
			</bean>
	</beans>
```

 这样就可以清楚的知道注入的是哪一个参数。

(2) 自定义类型

自定义类型即所依赖的对象为自定义的类，比如在上一条中介绍的MyService类依赖MysqlDaoImpl类，在xml配置文件中配置如下：

```
			</bean>
			<!-- 通过含参构造器注入 -->
			<bean id = "myservice" class="com.springframework.ioc.MyService">
				<constructor-arg ref = "mysql"/>
			</bean>
```

如果有两个参数都是自定义类型，则可以按照以上针对基本类型的做法，设置构造器的index属性。如下：

```
<bean id = "myservice" class="com.springframework.ioc.MyService">
				<constructor-arg index="0" ref = "mysql"/>
				<constructor-arg index="1" ref = "description"/>
			</bean>
```

 其中description是另外一个引用的bean的id。

 (3)集合类型  

总体概括有四种集合类型：List、Set、Map、Props。

集合中可以存放基本类型，也可以存放自定义类型。

存放基本类型的xml配置如下，分别有List、Set和Map类型，其中List、Set类型容器中存放的是String类型数据，Map类型容器中键值为String类型，值为Integer类型数据：

```
<bean id = "myservice" class="com.springframework.ioc.MyService">
				<constructor-arg index="0" ref = "mysql"/>
				<constructor-arg index="1" ref = "description"/>
				<constructor-arg  index="2">
					<list>
						<value>xiaoming</value>
						<value>xiaohong</value>
						<value>xiaolin</value>
					</list>
				</constructor-arg>
				<constructor-arg  index="3">
					<set>
						<value>jin</value>
						<value>yin</value>
						<value>yin</value>
					</set>
				</constructor-arg>
				<constructor-arg  index="4">
					<map>
						<entry key="wang" value="1"/>
						<entry key="li" value="2"/>
						<entry key="hu" value="3"/> 
					</map>
				</constructor-arg>
			</bean>
```

 Props与Map类型的容器差不多，只是Props只能存放String类型的键和值。

如果容器中存放的是自定义类型，xml文件中的配置如下：

```
<bean id = "myservice" class="com.springframework.ioc.MyService">
				<constructor-arg index="0" ref = "mysql"/>
				<constructor-arg index="1" ref = "description"/>
				<constructor-arg  index="2">
					<list>
						<ref bean="bean1">
						<ref bean="bean2">
						<ref bean="bean3">
					</list>
				</constructor-arg>
				<constructor-arg  index="3">
					<set>
                                              <ref bean="bean1">
					      <ref bean="bean2">
					      <ref bean="bean3">
					</set>
				</constructor-arg>
				<constructor-arg  index="4">
					<map>
						<entry key="wang" value-ref="bean7"/>
						<entry key-ref="bean10" value-ref="bean8"/>
						<entry key="hu" value-ref="bean9"/> 
					</map>
				</constructor-arg>
			</bean>
```

 (4)null空值

如果想要给某一个类型赋空值，xml配置文件配置如下：

```
<constructor-arg  index="0">

      <null/>
</constructor-arg>
```