---
title: "【第三章】 DI 之 3.1 DI的配置使用 ——跟我学spring3"
author: "maakey"
date: "2012-02-23T12:06:00Z"
tags: []
slug: "di-3-1-di-spring3"
draft: false
lastmod: "2012-12-23T23:07:40Z"
id: 1752728
url: "https://maakey.iteye.com/blog/1752728"
---

### 3.1.1 依赖和依赖注入

传统应用程序设计中所说的依赖一般指“类之间的关系”，那先让我们复习一下类之间的关系：

泛化：表示类与类之间的继承关系、接口与接口之间的继承关系；

实现：表示类对接口的实现；

依赖：当类与类之间有使用关系时就属于依赖关系，不同于关联关系，依赖不具有“拥有关系”，而是一种“相识关系”，只在某个特定地方（比如某个方法体内）才有关系。

关联：表示类与类或类与接口之间的依赖关系，表现为“拥有关系”；具体到代码可以用实例变量来表示；

聚合：属于是关联的特殊情况，体现部分-整体关系，是一种弱拥有关系；整体和部分可以有不一样的生命周期；是一种弱关联；

组合：属于是关联的特殊情况，也体现了体现部分-整体关系，是一种强“拥有关系”；整体与部分有相同的生命周期，是一种强关联；

Spring IoC容器的依赖有两层含义：Bean依赖容器和容器注入Bean的依赖资源：

Bean依赖容器：也就是说Bean要依赖于容器，这里的依赖是指容器负责创建Bean并管理Bean的生命周期，正是由于由容器来控制创建Bean并注入依赖，也就是控制权被反转了，这也正是IoC名字的由来，此处的有依赖是指Bean和容器之间的依赖关系。

容器注入Bean的依赖资源：容器负责注入Bean的依赖资源，依赖资源可以是Bean、外部文件、常量数据等，在Java中都反映为对象，并且由容器负责组装Bean之间的依赖关系，此处的依赖是指Bean之间的依赖关系，可以认为是传统类与类之间的“关联”、“聚合”、“组合”关系。

为什么要应用依赖注入，应用依赖注入能给我们带来哪些好处呢？

动态替换Bean依赖对象，程序更灵活：替换Bean依赖对象，无需修改源文件：应用依赖注入后，由于可以采用配置文件方式实现，从而能随时动态的替换Bean的依赖对象，无需修改java源文件；

更好实践面向接口编程，代码更清晰：在Bean中只需指定依赖对象的接口，接口定义依赖对象完成的功能，通过容器注入依赖实现；

更好实践优先使用对象组合，而不是类继承：因为IoC容器采用注入依赖，也就是组合对象，从而更好的实践对象组合。

- 采用对象组合，Bean的功能可能由几个依赖Bean的功能组合而成，其Bean本身可能只提供少许功能或根本无任何功能，全部委托给依赖Bean，对象组合具有动态性，能更方便的替换掉依赖Bean，从而改变Bean功能；
- 而如果采用类继承，Bean没有依赖Bean，而是采用继承方式添加新功能，，而且功能是在编译时就确定了，不具有动态性，而且采用类继承导致Bean与子Bean之间高度耦合，难以复用。

增加Bean可复用性：依赖于对象组合，Bean更可复用且复用更简单；

降低Bean之间耦合：由于我们完全采用面向接口编程，在代码中没有直接引用Bean依赖实现，全部引用接口，而且不会出现显示的创建依赖对象代码，而且这些依赖是由容器来注入，很容易替换依赖实现类，从而降低Bean与依赖之间耦合；

代码结构更清晰：要应用依赖注入，代码结构要按照规约方式进行书写，从而更好的应用一些最佳实践，因此代码结构更清晰。

从以上我们可以看出，其实依赖注入只是一种装配对象的手段，设计的类结构才是基础，如果设计的类结构不支持依赖注入，Spring IoC容器也注入不了任何东西，从而从根本上说“如何设计好类结构才是关键，依赖注入只是一种装配对象手段”。

前边IoC一章我们已经了解了Bean依赖容器，那容器如何注入Bean的依赖资源，Spring IoC容器注入依赖资源主要有以下两种基本实现方式：

构造器注入：就是容器实例化Bean时注入那些依赖，通过在在Bean定义中指定构造器参数进行注入依赖，包括实例工厂方法参数注入依赖，但静态工厂方法参数不允许注入依赖；

setter注入：通过setter方法进行注入依赖；

方法注入：能通过配置方式替换掉Bean方法，也就是通过配置改变Bean方法 功能。

我们已经知道注入实现方式了，接下来让我们来看看具体配置吧。

### 3.1.2 构造器注入

使用构造器注入通过配置构造器参数实现，构造器参数就是依赖。除了构造器方式，还有静态工厂、实例工厂方法可以进行构造器注入。如图3-1所示：

![](http://sishuok.com/forum/upload/2012/2/20/d50eb0125ddd8f111829e1e1d4f07071__1.JPG)

图3-1 实例化

构造器注入可以根据参数索引注入、参数类型注入或Spring3支持的参数名注入，但参数名注入是有限制的，需要使用在编译程序时打开调试模式（即在编译时使用“javac –g:vars”在class文件中生成变量调试信息，默认是不包含变量调试信息的，从而能获取参数名字，否则获取不到参数名字）或在构造器上使用@ConstructorProperties（java.beans.ConstructorProperties）注解来指定参数名。

首先让我们准备测试构造器类HelloImpl3.java，该类只有一个包含两个参数的构造器：

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2447.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2447.html)[打印](http://sishuok.com/forum/blogPost/list/2447.html)

01. packagecn.javass.spring.chapter3.helloworld;
02. publicclassHelloImpl3implementsHelloApi{
03. privateStringmessage;
04. privateintindex;
05. //@java.beans.ConstructorProperties({"message","index"})
06. publicHelloImpl3(Stringmessage,intindex){
07. this.message=message;
08. this.index=index;
09. }
10. @Override
11. publicvoidsayHello(){
12. System.out.println(index+":"+message);
13. }
14. }

一、根据参数索引注入，使用标签“&lt;constructor-arg index="1" value="1"/&gt;”来指定注入的依赖，其中“index”表示索引，从0开始，即第一个参数索引为0，“value”来指定注入的常量值，配置方式如下：

![](http://sishuok.com/forum/upload/2012/2/20/b92723f60abbd6dccfae5538f280501d__2.JPG)

二、根据参数类型进行注入，使用标签“&lt;constructor-arg type="java.lang.String" value="Hello World!"/&gt;”来指定注入的依赖，其中“type”表示需要匹配的参数类型，可以是基本类型也可以是其他类型，如“int”、“java.lang.String”，“value”来指定注入的常量值，配置方式如下：

![](http://sishuok.com/forum/upload/2012/2/20/986bdd18becfeed7a1c5a3400a30343a__3.JPG)

三、根据参数名进行注入，使用标签“&lt;constructor-arg name="message" value="Hello World!"/&gt;”来指定注入的依赖，其中“name”表示需要匹配的参数名字，“value”来指定注入的常量值，配置方式如下：

![](http://sishuok.com/forum/upload/2012/2/20/839e93acd6d43a933dd71f4f36e3e8d6__4.JPG)

四、让我们来用具体的例子来看一下构造器注入怎么使用吧。

（1）首先准备Bean类，在此我们就使用“HelloImpl3”这个类。

（2）有了Bean类，接下来要进行Bean定义配置，我们需要配置三个Bean来完成上述三种依赖注入测试，其中Bean ”byIndex”是通过索引注入依赖；Bean ”byType”是根据类型进行注入依赖；Bean ”byName”是根据参数名字进行注入依赖，具体配置文件（resources/chapter3/ constructorDependencyInject.xml）如下：

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2447.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2447.html)[打印](http://sishuok.com/forum/blogPost/list/2447.html)

01. &lt;!--通过构造器参数索引方式依赖注入--&gt;
02. &lt;beanid="byIndex"class="cn.javass.spring.chapter3.HelloImpl3"&gt;
03. &lt;constructor-argindex="0"value="HelloWorld!"/&gt;
04. &lt;constructor-argindex="1"value="1"/&gt;
05. &lt;/bean&gt;
06. &lt;!--通过构造器参数类型方式依赖注入--&gt;
07. &lt;beanid="byType"class="cn.javass.spring.chapter3.HelloImpl3"&gt;
08. &lt;constructor-argtype="java.lang.String"value="HelloWorld!"/&gt;
09. &lt;constructor-argtype="int"value="2"/&gt;
10. &lt;/bean&gt;
11. &lt;!--通过构造器参数名称方式依赖注入--&gt;
12. &lt;beanid="byName"class="cn.javass.spring.chapter3.HelloImpl3"&gt;
13. &lt;constructor-argname="message"value="HelloWorld!"/&gt;
14. &lt;constructor-argname="index"value="3"/&gt;
15. &lt;/bean&gt;

（3）配置完毕后，在测试之前，因为我们使用了通过构造器参数名字注入方式，请确保编译时class文件包含“变量信息”，具体查看编译时是否包含“变量调试信息”请右击项目，在弹出的对话框选择属性；然后在弹出的对话框选择“Java Compiler”条目，在“Class 文件 生成”框中选择“添加变量信息到Class文件（调试器使用）”，具体如图3-2：

![](http://sishuok.com/forum/upload/2012/2/20/1ad09d94fde83c2f431ef860e33574cf__5.JPG)

图3-2 编译时打开“添加变量信息选项”

（4）接下来让我们测试一下配置是否工作，具体测试代码（cn.javass.spring.chapter3. DependencyInjectTest）如下：

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2447.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2447.html)[打印](http://sishuok.com/forum/blogPost/list/2447.html)

01. @Test
02. publicvoidtestConstructorDependencyInjectTest(){
03. BeanFactorybeanFactory=newClassPathXmlApplicationContext("chapter3/constructorDependencyInject.xml");
04. //获取根据参数索引依赖注入的Bean
05. HelloApibyIndex=beanFactory.getBean("byIndex",HelloApi.class);
06. byIndex.sayHello();
07. //获取根据参数类型依赖注入的Bean
08. HelloApibyType=beanFactory.getBean("byType",HelloApi.class);
09. byType.sayHello();
10. //获取根据参数名字依赖注入的Bean
11. HelloApibyName=beanFactory.getBean("byName",HelloApi.class);
12. byName.sayHello();
13. }

通过以上测试我们已经会基本的构造器注入配置了，在测试通过参数名字注入时，除了可以使用以上方式，还可以通过在构造器上添加@java.beans.ConstructorProperties({"message", "index"})注解来指定参数名字，在HelloImpl3构造器上把注释掉的“ConstructorProperties”打开就可以了，这个就留给大家做练习，自己配置然后测试一下。

五、大家已经会了构造器注入，那让我们再看一下静态工厂方法注入和实例工厂注入吧，其实它们注入配置是完全一样，在此我们只示范一下静态工厂注入方式和实例工厂方式配置，测试就留给大家自己练习：

（1）静态工厂类

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2447.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2447.html)[打印](http://sishuok.com/forum/blogPost/list/2447.html)

1. //静态工厂类
2. packagecn.javass.spring.chapter3;
3. importcn.javass.spring.chapter2.helloworld.HelloApi;
4. publicclassDependencyInjectByStaticFactory{
5. publicstaticHelloApinewInstance(Stringmessage,intindex){
6. returnnewHelloImpl3(message,index);
7. }
8. }

静态工厂类Bean定义配置文件（chapter3/staticFactoryDependencyInject.xml）

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2447.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2447.html)[打印](http://sishuok.com/forum/blogPost/list/2447.html)

01. &lt;beanid="byIndex"
02. class="cn.javass.spring.chapter3.DependencyInjectByStaticFactory"factory-method="newInstance"&gt;
03. &lt;constructor-argindex="0"value="HelloWorld!"/&gt;
04. &lt;constructor-argindex="1"value="1"/&gt;
05. &lt;/bean&gt;
06. &lt;beanid="byType"
07. class="cn.javass.spring.chapter3.DependencyInjectByStaticFactory"factory-method="newInstance"&gt;
08. &lt;constructor-argtype="java.lang.String"value="HelloWorld!"/&gt;
09. &lt;constructor-argtype="int"value="2"/&gt;
10. &lt;/bean&gt;
11. &lt;beanid="byName"
12. class="cn.javass.spring.chapter3.DependencyInjectByStaticFactory"factory-method="newInstance"&gt;
13. &lt;constructor-argname="message"value="HelloWorld!"/&gt;
14. &lt;constructor-argname="index"value="3"/&gt;
15. &lt;/bean&gt;

（2）实例工厂类

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2447.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2447.html)[打印](http://sishuok.com/forum/blogPost/list/2447.html)

1. //实例工厂类
2. packagecn.javass.spring.chapter3;
3. importcn.javass.spring.chapter2.helloworld.HelloApi;
4. publicclassDependencyInjectByInstanceFactory{
5. publicHelloApinewInstance(Stringmessage,intindex){
6. returnnewHelloImpl3(message,index);
7. }
8. }

实例工厂类Bean定义配置文件（chapter3/instanceFactoryDependencyInject.xml）

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2447.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2447.html)[打印](http://sishuok.com/forum/blogPost/list/2447.html)

01. &lt;beanid="instanceFactory"
02. class="cn.javass.spring.chapter3.DependencyInjectByInstanceFactory"/&gt;
03. &lt;beanid="byIndex"
04. factory-bean="instanceFactory"factory-method="newInstance"&gt;
05. &lt;constructor-argindex="0"value="HelloWorld!"/&gt;
06. &lt;constructor-argindex="1"value="1"/&gt;
07. &lt;/bean&gt;
08. &lt;beanid="byType"
09. factory-bean="instanceFactory"factory-method="newInstance"&gt;
10. &lt;constructor-argtype="java.lang.String"value="HelloWorld!"/&gt;
11. &lt;constructor-argtype="int"value="2"/&gt;
12. &lt;/bean&gt;
13. &lt;beanid="byName"
14. factory-bean="instanceFactory"factory-method="newInstance"&gt;
15. &lt;constructor-argname="message"value="HelloWorld!"/&gt;
16. &lt;constructor-argname="index"value="3"/&gt;
17. &lt;/bean&gt;

（3）测试代码和构造器方式完全一样，只是配置文件不一样，大家只需把测试文件改一下就可以了。还有一点需要大家注意就是静态工厂方式和实例工厂方式根据参数名字注入的方式只支持通过在class文件中添加“变量调试信息”方式才能运行，ConstructorProperties注解方式不能工作，它只对构造器方式起作用，不建议使用根据参数名进行构造器注入。

### 3.1.3 setter注入

setter注入，是通过在通过构造器、静态工厂或实例工厂实例好Bean后，通过调用Bean类的setter方法进行注入依赖，如图3-3所示：

![](http://sishuok.com/forum/upload/2012/2/20/b71a6a4853593eb7969695a4f30629be__6.JPG)

图3-3 setter注入方式

setter注入方式只有一种根据setter名字进行注入：

![](http://sishuok.com/forum/upload/2012/2/20/bc077ec8e4857076d2dab31fc1aca634__7.JPG)

知道配置方式了，接下来先让我们来做个简单例子吧。

（1）准备测试类HelloImpl4，需要两个setter方法“setMessage”和“setIndex”：

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2447.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2447.html)[打印](http://sishuok.com/forum/blogPost/list/2447.html)

01. packagecn.javass.spring.chapter3;
02. importcn.javass.spring.chapter2.helloworld.HelloApi;
03. publicclassHelloImpl4implementsHelloApi{
04. privateStringmessage;
05. privateintindex;
06. //setter方法
07. publicvoidsetMessage(Stringmessage){
08. this.message=message;
09. }
10. publicvoidsetIndex(intindex){
11. this.index=index;
12. }
13. @Override
14. publicvoidsayHello(){
15. System.out.println(index+":"+message);
16. }
17. }

（2）配置Bean定义，具体配置文件（resources/chapter3/setterDependencyInject.xml）片段如下：

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2447.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2447.html)[打印](http://sishuok.com/forum/blogPost/list/2447.html)

1. &lt;!--通过setter方式进行依赖注入--&gt;
2. &lt;beanid="bean"class="cn.javass.spring.chapter3.HelloImpl4"&gt;
3. &lt;propertyname="message"value="HelloWorld!"/&gt;
4. &lt;propertyname="index"&gt;
5. &lt;value&gt;1&lt;/value&gt;
6. &lt;/property&gt;
7. &lt;/bean&gt;

（3）该写测试进行测试一下是否满足能工作了，其实测试代码一点没变，变的是配置：

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2447.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2447.html)[打印](http://sishuok.com/forum/blogPost/list/2447.html)

1. @Test
2. publicvoidtestSetterDependencyInject(){
3. BeanFactorybeanFactory=
4. newClassPathXmlApplicationContext("chapter3/setterDependencyInject.xml");
5. HelloApibean=beanFactory.getBean("bean",HelloApi.class);
6. bean.sayHello();
7. }

知道如何配置了，但Spring如何知道setter方法？如何将值注入进去的呢？其实方法名是要遵守约定的，setter注入的方法名要遵循“JavaBean getter/setter 方法命名约定”：

JavaBean：是本质就是一个POJO类，但具有一下限制：

该类必须要有公共的无参构造器，如public HelloImpl4() {}；

属性为private访问级别，不建议public，如private String message;

属性必要时通过一组setter（修改器）和getter（访问器）方法来访问；

setter方法，以“set”开头，后跟首字母大写的属性名，如“setMesssage”,简单属性一般只有一个方法参数，方法返回值通常为“void”;

getter方法，一般属性以“get”开头，对于boolean类型一般以“is”开头，后跟首字母大写的属性名，如“getMesssage”，“isOk”；

还有一些其他特殊情况，比如属性有连续两个大写字母开头，如“URL”,则setter/getter方法为：“setURL”和“getURL”，其他一些特殊情况请参看“Java Bean”命名规范。

### 3.1.4 注入常量

注入常量是依赖注入中最简单的。配置方式如下所示：

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2447.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2447.html)[打印](http://sishuok.com/forum/blogPost/list/2447.html)

1. &lt;propertyname="message"value="HelloWorld!"/&gt;
2. 或
3. &lt;propertyname="index"&gt;&lt;value&gt;1&lt;/value&gt;&lt;/property&gt;&lt;spanclass="Apple-style-span"style="font-size:14px;white-space:normal;background-color:#ffffff;"&gt;&lt;/span&gt;

以上两种方式都可以，从配置来看第一种更简洁。注意此处“value”中指定的全是字符串，由Spring容器将此字符串转换成属性所需要的类型，如果转换出错，将抛出相应的异常。

Spring容器目前能对各种基本类型把配置的String参数转换为需要的类型。

注：Spring类型转换系统对于boolean类型进行了容错处理，除了可以使用“true/false”标准的Java值进行注入，还能使用“yes/no”、“on/off”、“1/0”来代表“真/假”，所以大家在学习或工作中遇到这种类似问题不要觉得是人家配置错了，而是Spring容错做的非常好。

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2447.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2447.html)[打印](http://sishuok.com/forum/blogPost/list/2447.html)

01. 测试类
02. publicclassBooleanTestBean{
03. privatebooleansuccess;
04. publicvoidsetSuccess(booleansuccess){
05. this.success=success;
06. }
07. publicbooleanisSuccess(){
08. returnsuccess;
09. }
10. }
11. 配置文件（chapter3/booleanInject.xml）片段：
12. &lt;!--boolean参数值可以用on/off--&gt;
13. &lt;beanid="bean2"class="cn.javass.spring.chapter3.bean.BooleanTestBean"&gt;
14. &lt;propertyname="success"value="on"/&gt;
15. &lt;/bean&gt;
16. &lt;!--boolean参数值可以用yes/no--&gt;
17. &lt;beanid="bean3"class="cn.javass.spring.chapter3.bean.BooleanTestBean"&gt;
18. &lt;propertyname="success"value="yes"/&gt;
19. &lt;/bean&gt;
20. &lt;!--boolean参数值可以用1/0--&gt;
21. &lt;beanid="bean4"class="cn.javass.spring.chapter3.bean.BooleanTestBean"&gt;
22. &lt;propertyname="success"value="1"/&gt;
23. &lt;/bean&gt;

### 3.1.5 注入Bean ID

用于注入Bean的ID，ID是一个常量不是引用，且类似于注入常量，但提供错误验证功能，配置方式如下所示：

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2447.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2447.html)[打印](http://sishuok.com/forum/blogPost/list/2447.html)

1. &lt;propertyname="id"&gt;&lt;idrefbean="bean1"/&gt;&lt;/property&gt;

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2447.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2447.html)[打印](http://sishuok.com/forum/blogPost/list/2447.html)

1. &lt;propertyname="id"&gt;&lt;idreflocal="bean2"/&gt;&lt;/property&gt;

两种方式都可以，上述配置本质上在运行时等于如下方式

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2447.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2447.html)[打印](http://sishuok.com/forum/blogPost/list/2447.html)

1. &lt;beanid="bean1"class="……"/&gt;
2. &lt;beanid="idrefBean1"class="……"&gt;
3. &lt;propertyname="id"value="bean1"/&gt;
4. &lt;/bean&gt;

第一种方式可以在容器初始化时校验被引用的Bean是否存在，如果不存在将抛出异常，而第二种方式只有在Bean实际使用时才能发现传入的Bean的ID是否正确，可能发生不可预料的错误。因此如果想注入Bean的ID，推荐使用第一种方式。

接下来学习一下如何使用吧：

首先定义测试Bean：

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2447.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2447.html)[打印](http://sishuok.com/forum/blogPost/list/2447.html)

01. packagecn.javass.spring.chapter3.bean
02. publicclassIdRefTestBean{
03. privateStringid;
04. publicStringgetId(){
05. returnid;
06. }
07. publicvoidsetId(Stringid){
08. this.id=id;
09. }
10. }

其次定义配置文件（chapter3/idRefInject.xml）：

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2447.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2447.html)[打印](http://sishuok.com/forum/blogPost/list/2447.html)

1. &lt;beanid="bean1"class="java.lang.String"&gt;
2. &lt;constructor-argindex="0"value="test"/&gt;
3. &lt;/bean&gt;
4. &lt;beanid="bean2"class="java.lang.String"&gt;
5. &lt;constructor-argindex="0"value="test"/&gt;
6. &lt;/bean&gt;

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2447.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2447.html)[打印](http://sishuok.com/forum/blogPost/list/2447.html)

1. &lt;beanid="idrefBean1"class="cn.javass.spring.chapter3.bean.IdRefTestBean"&gt;
2. &lt;propertyname="id"&gt;&lt;idrefbean="bean1"/&gt;&lt;/property&gt;
3. &lt;/bean&gt;
4. &lt;beanid="idrefBean2"class="cn.javass.spring.chapter3.bean.IdRefTestBean"&gt;
5. &lt;propertyname="id"&gt;&lt;idreflocal="bean2"/&gt;&lt;/property&gt;
6. &lt;/bean&gt;

从配置中可以看出，注入的Bean的ID是一个java.lang.String类型，即字符串类型，因此注入的同样是常量，只是具有校验功能。

&lt;idref bean="……"/&gt;将在容器初始化时校验注入的ID对于的Bean是否存在，如果不存在将抛出异常。

&lt;idref local="……"/&gt;将在XML解析时校验注入的ID对于的Bean在当前配置文件中是否存在，如果不存在将抛出异常，它不同于&lt;idref bean="……"/&gt;是校验发生在XML解析式而非容器初始化时，且只检查当前配置文件中是否存在相应的Bean。

### 3.1.6 注入集合、数组和字典

Spring不仅能注入简单类型数据，还能注入集合（Collection、无序集合Set、有序集合List）类型、数组(Array)类型、字典(Map)类型数据、Properties类型数据，接下来就让我们一个个看看如何注入这些数据类型的数据。

一、注入集合类型：包括Collection类型、Set类型、List类型数据：

（1）List类型：需要使用&lt;list&gt;标签来配置注入，其具体配置如下：

![](http://sishuok.com/forum/upload/2012/2/20/ea8eeb40b7c3710f2a898118481a2b67__8.JPG)

让我们来写个测试来练习一下吧：

准备测试类：

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2447.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2447.html)[打印](http://sishuok.com/forum/blogPost/list/2447.html)

01. packagecn.javass.spring.chapter3.bean;
02. importjava.util.List;
03. publicclassListTestBean{
04. privateList&lt;String&gt;values;
05. publicList&lt;String&gt;getValues(){
06. returnvalues;
07. }
08. publicvoidsetValues(List&lt;String&gt;values){
09. this.values=values;
10. }
11. }

进行Bean定义，在配置文件（resources/chapter3/listInject.xml）中配置list注入：

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2447.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2447.html)[打印](http://sishuok.com/forum/blogPost/list/2447.html)

1. &lt;beanid="listBean"class="cn.javass.spring.chapter3.bean.ListTestBean"&gt;
2. &lt;propertyname="values"&gt;
3. &lt;list&gt;
4. &lt;value&gt;1&lt;/value&gt;
5. &lt;value&gt;2&lt;/value&gt;
6. &lt;value&gt;3&lt;/value&gt;
7. &lt;/list&gt;
8. &lt;/property&gt;
9. &lt;/bean&gt;

测试代码：

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2447.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2447.html)[打印](http://sishuok.com/forum/blogPost/list/2447.html)

1. @Test
2. publicvoidtestListInject(){
3. BeanFactorybeanFactory=
4. newClassPathXmlApplicationContext("chapter3/listInject.xml");
5. ListTestBeanlistBean=beanFactory.getBean("listBean",ListTestBean.class);
6. System.out.println(listBean.getValues().size());
7. Assert.assertEquals(3,listBean.getValues().size());
8. }

（2）Set类型：需要使用&lt;set&gt;标签来配置注入，其配置参数及含义和&lt;lsit&gt;标签完全一样，在此就不阐述了：

准备测试类：

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2447.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2447.html)[打印](http://sishuok.com/forum/blogPost/list/2447.html)

01. packagecn.javass.spring.chapter3.bean;
02. importjava.util.Collection;
03. publicclassCollectionTestBean{
04. privateCollection&lt;String&gt;values;
05. publicvoidsetValues(Collection&lt;String&gt;values){
06. this.values=values;
07. }
08. publicCollection&lt;String&gt;getValues(){
09. returnvalues;
10. }
11. }

进行Bean定义，在配置文件（resources/chapter3/listInject.xml）中配置list注入：

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2447.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2447.html)[打印](http://sishuok.com/forum/blogPost/list/2447.html)

1. &lt;beanid="setBean"class="cn.javass.spring.chapter3.bean.SetTestBean"&gt;
2. &lt;propertyname="values"&gt;
3. &lt;set&gt;
4. &lt;value&gt;1&lt;/value&gt;
5. &lt;value&gt;2&lt;/value&gt;
6. &lt;value&gt;3&lt;/value&gt;
7. &lt;/set&gt;
8. &lt;/property&gt;
9. &lt;/bean&gt;

具体测试代码就不写了，和listBean测试代码完全一样。

（2）Collection类型：因为Collection类型是Set和List类型的基类型，所以使用&lt;set&gt;或&lt;list&gt;标签都可以进行注入，配置方式完全和以上配置方式一样，只是将测试类属性改成“Collection”类型，如果配置有问题，可参考cn.javass.spring.chapter3.DependencyInjectTest测试类中的testCollectionInject测试方法中的代码。

二、注入数组类型：需要使用&lt;array&gt;标签来配置注入，其中标签属性“value-type”和“merge”和&lt;list&gt;标签含义完全一样，具体配置如下：

![](http://sishuok.com/forum/upload/2012/2/20/3c02092e74f93282b673c99692f64d4a__9.JPG)

如果练习时遇到配置问题，可以参考“cn.javass.spring.chapter3.DependencyInjectTest”测试类中的testArrayInject测试方法中的代码。

三、注入字典（Map）类型：字典类型是包含键值对数据的数据结构，需要使用&lt;map&gt;标签来配置注入，其属性“key-type”和“value-type”分别指定“键”和“值”的数据类型，其含义和&lt;list&gt;标签的“value-type”含义一样，在此就不罗嗦了，并使用&lt;key&gt;子标签来指定键数据，&lt;value&gt;子标签来指定键对应的值数据，具体配置如下：

![](http://sishuok.com/forum/upload/2012/2/20/921eebe8c461cd57945255d261f46a96__10.JPG)

如果练习时遇到配置问题，可以参考“cn.javass.spring.chapter3.DependencyInjectTest”测试类中的testMapInject测试方法中的代码。

四、Properties注入：Spring能注入java.util.Properties类型数据，需要使用&lt;props&gt;标签来配置注入，键和值类型必须是String，不能变，子标签&lt;prop key=”键”&gt;值&lt;/prop&gt;来指定键值对，具体配置如下：

![](http://sishuok.com/forum/upload/2012/2/20/45f141f06940ec5773d313f02e9f8ada__11.JPG)

![](http://sishuok.com/forum/upload/2012/2/20/18c668a0100d6e74025f7352c2347b6a__12.JPG)

如果练习时遇到配置问题，可以参考cn.javass.spring.chapter3.DependencyInjectTest测试类中的testPropertiesInject测试方法中的代码。

到此我们已经把简单类型及集合类型介绍完了，大家可能会问怎么没见注入“Bean之间关系”的例子呢？接下来就让我们来讲解配置Bean之间依赖关系，也就是注入依赖Bean。

### 3.1.7 引用其它Bean

上边章节已经介绍了注入常量、集合等基本数据类型和集合数据类型，本小节将介绍注入依赖Bean及注入内部Bean。

引用其他Bean的步骤与注入常量的步骤一样，可以通过构造器注入及setter注入引用其他Bean，只是引用其他Bean的注入配置稍微变化了一下：可以将“&lt;constructor-arg index="0" value="Hello World!"/&gt;”和“&lt;property name="message" value="Hello World!"/&gt;”中的value属性替换成bean属性，其中bean属性指定配置文件中的其他Bean的id或别名。另一种是把&lt;value&gt;标签替换为&lt;.ref bean=”beanName”&gt;，bean属性也是指定配置文件中的其他Bean的id或别名。那让我们看一下具体配置吧：

一、构造器注入方式：

（1）通过” &lt;constructor-arg&gt;”标签的ref属性来引用其他Bean，这是最简化的配置：

![](http://sishuok.com/forum/upload/2012/2/20/55683bad406b9d7bb748f5b9440059e0__13.JPG)

（2）通过” &lt;constructor-arg&gt;”标签的子&lt;ref&gt;标签来引用其他Bean，使用bean属性来指定引用的Bean：

![](http://sishuok.com/forum/upload/2012/2/20/7379a485e2a5ed554c09889265f27bf0__14.JPG)

二、setter注入方式：

（1）通过” &lt;property&gt;”标签的ref属性来引用其他Bean，这是最简化的配置：

![](http://sishuok.com/forum/upload/2012/2/20/9f1acbf99307e07ca1fbdd42cb3c63a4__15.JPG)

（2）通过” &lt;property&gt;”标签的子&lt;ref&gt;标签来引用其他Bean，使用bean属性来指定引用的Bean：

![](http://sishuok.com/forum/upload/2012/2/20/c7e3bd005904f3b7936069a38cadc669__16.JPG)

三、接下来让我们用个具体例子来讲解一下具体使用吧：

（1）首先让我们定义测试引用Bean的类，在此我们可以使用原有的HelloApi实现，然后再定义一个装饰器来引用其他Bean，具体装饰类如下：

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2447.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2447.html)[打印](http://sishuok.com/forum/blogPost/list/2447.html)

01. packagecn.javass.spring.chapter3.bean;
02. importcn.javass.spring.chapter2.helloworld.HelloApi;
03. publicclassHelloApiDecoratorimplementsHelloApi{
04. privateHelloApihelloApi;
05. //空参构造器
06. publicHelloApiDecorator(){
07. }
08. //有参构造器
09. publicHelloApiDecorator(HelloApihelloApi){
10. this.helloApi=helloApi;
11. }
12. publicvoidsetHelloApi(HelloApihelloApi){
13. this.helloApi=helloApi;
14. }
15. @Override
16. publicvoidsayHello(){
17. System.out.println("==========装饰一下===========");
18. helloApi.sayHello();
19. System.out.println("==========装饰一下===========");
20. }
21. }

（2）定义好了测试引用Bean接下来该在配置文件(resources/chapter3/beanInject.xml)进行配置Bean定义了，在此将演示通过构造器及setter方法方式注入依赖Bean：

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2447.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2447.html)[打印](http://sishuok.com/forum/blogPost/list/2447.html)

01. &lt;!--定义依赖Bean--&gt;
02. &lt;beanid="helloApi"class="cn.javass.spring.chapter2.helloworld.HelloImpl"/&gt;
03. &lt;!--通过构造器注入--&gt;
04. &lt;beanid="bean1"class="cn.javass.spring.chapter3.bean.HelloApiDecorator"&gt;
05. &lt;constructor-argindex="0"ref="helloApi"/&gt;
06. &lt;/bean&gt;
07. &lt;!--通过构造器注入--&gt;
08. &lt;beanid="bean2"class="cn.javass.spring.chapter3.bean.HelloApiDecorator"&gt;
09. &lt;propertyname="helloApi"&gt;&lt;refbean="helloApi"/&gt;&lt;/property&gt;
10. &lt;/bean&gt;

（3）测试一下吧，测试代码(cn.javass.spring.chapter3.DependencyInjectTest)片段如下：

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2447.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2447.html)[打印](http://sishuok.com/forum/blogPost/list/2447.html)

01. @Test
02. publicvoidtestBeanInject(){
03. BeanFactorybeanFactory=
04. newClassPathXmlApplicationContext("chapter3/beanInject.xml");
05. //通过构造器方式注入
06. HelloApibean1=beanFactory.getBean("bean1",HelloApi.class);
07. bean1.sayHello();
08. //通过setter方式注入
09. HelloApibean2=beanFactory.getBean("bean2",HelloApi.class);
10. bean2.sayHello();
11. }

四、其他引用方式：除了最基本配置方式以外，Spring还提供了另外两种更高级的配置方式，&lt;ref local=””/&gt;和&lt;ref parent=””/&gt;：

（1）&lt;ref local=””/&gt;配置方式：用于引用通过&lt;bean id=”beanName”&gt;方式中通过id属性指定的Bean，它能利用XML解析器的验证功能在读取配置文件时来验证引用的Bean是否存在。因此如果在当前配置文件中有相互引用的Bean可以采用&lt;ref local&gt;方式从而如果配置错误能在开发调试时就发现错误。

如果引用一个在当前配置文件中不存在的Bean将抛出如下异常：

org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line21 inXML document from class path resource \[chapter3/beanInject2.xml] is invalid; nested exception is org.xml.sax.SAXParseException: cvc-id.1: There is no ID/IDREF binding for IDREF 'helloApi'.

&lt;ref local&gt;具体配置方式如下：

![](http://sishuok.com/forum/upload/2012/2/20/502163429b4a45dffb3e8fb3750be0c2__17.JPG)

（2）&lt;ref parent=””/&gt;配置方式：用于引用父容器中的Bean，不会引用当前容器中的Bean，当然父容器中的Bean和当前容器的Bean是可以重名的，获取顺序是先查找当前容器中的Bean，如果找不到再从父容器找。具体配置方式如下：

![](http://sishuok.com/forum/upload/2012/2/20/59b072df3cd4f6af045f6afaeac0a01b__18.JPG)

接下来让我们用个例子演示一下&lt;ref local&gt;和&lt;ref parent&gt;的配置过程：

首先还是准备测试类，在此我们就使用以前写好的HelloApiDecorator和HelloImpl4类；其次进行Bean定义，其中当前容器bean1引用本地的”helloApi”，而”bean2”将引用父容器的”helloApi”，配置如下：

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2447.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2447.html)[打印](http://sishuok.com/forum/blogPost/list/2447.html)

1. &lt;!--sources/chapter3/parentBeanInject.xml表示父容器配置--&gt;
2. &lt;!--注意此处可能子容器也定义一个该Bean--&gt;
3. &lt;beanid="helloApi"class="cn.javass.spring.chapter3.HelloImpl4"&gt;
4. &lt;propertyname="index"value="1"/&gt;
5. &lt;propertyname="message"value="HelloParent!"/&gt;
6. &lt;/bean&gt;

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2447.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2447.html)[打印](http://sishuok.com/forum/blogPost/list/2447.html)

01. &lt;!--sources/chapter3/localBeanInject.xml表示当前容器配置--&gt;
02. &lt;!--注意父容器中也定义了id为helloApi的Bean--&gt;
03. &lt;beanid="helloApi"class="cn.javass.spring.chapter3.HelloImpl4"&gt;
04. &lt;propertyname="index"value="1"/&gt;
05. &lt;propertyname="message"value="HelloLocal!"/&gt;
06. &lt;/bean&gt;
07. &lt;!--通过local注入--&gt;
08. &lt;beanid="bean1"class="cn.javass.spring.chapter3.bean.HelloApiDecorator"&gt;
09. &lt;constructor-argindex="0"&gt;&lt;reflocal="helloApi"/&gt;&lt;/constructor-arg&gt;
10. &lt;/bean&gt;
11. &lt;!--通过parent注入--&gt;
12. &lt;beanid="bean2"class="cn.javass.spring.chapter3.bean.HelloApiDecorator"&gt;
13. &lt;propertyname="helloApi"&gt;&lt;refparent="helloApi"/&gt;&lt;/property&gt;
14. &lt;/bean&gt;

（3）写测试类测试一下吧，具体代码片段如下：

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2447.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2447.html)[打印](http://sishuok.com/forum/blogPost/list/2447.html)

01. @Test
02. publicvoidtestLocalAndparentBeanInject(){
03. //初始化父容器
04. ApplicationContextparentBeanContext=
05. newClassPathXmlApplicationContext("chapter3/parentBeanInject.xml");
06. //初始化当前容器
07. ApplicationContextbeanContext=newClassPathXmlApplicationContext(
08. newString\[]{"chapter3/localBeanInject.xml"},parentBeanContext);
09. HelloApibean1=beanContext.getBean("bean1",HelloApi.class);
10. bean1.sayHello();//该Bean引用localbean
11. HelloApibean2=beanContext.getBean("bean2",HelloApi.class);
12. bean2.sayHello();//该Bean引用parentbean
13. }

“bean1”将输出“Hello Local!”表示引用当前容器的Bean，”bean2”将输出“Hello Paren!”，表示引用父容器的Bean，如配置有问题请参考cn.javass.spring.chapter3.DependencyInjectTest中的testLocalAndparentBeanInject测试方法。

### 3.1.8 内部Bean定义

内部Bean就是在&lt;property&gt;或&lt;constructor-arg&gt;内通过&lt;bean&gt;标签定义的Bean，该Bean不管是否指定id或name，该Bean都会有唯一的匿名标识符，而且不能指定别名，该内部Bean对其他外部Bean不可见，具体配置如下：

![](http://sishuok.com/forum/upload/2012/2/20/01b175b3deb09908dc72de89690be484__19.JPG)

（1）让我们写个例子测试一下吧，具体配置文件如下：

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2447.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2447.html)[打印](http://sishuok.com/forum/blogPost/list/2447.html)

1. &lt;beanid="bean"class="cn.javass.spring.chapter3.bean.HelloApiDecorator"&gt;
2. &lt;propertyname="helloApi"&gt;
3. &lt;beanid="helloApi"class="cn.javass.spring.chapter2.helloworld.HelloImpl"/&gt;
4. &lt;/property&gt;
5. &lt;/bean&gt;

（2）测试代码（cn.javass.spring.chapter3.DependencyInjectTest.testInnerBeanInject）：

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2447.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2447.html)[打印](http://sishuok.com/forum/blogPost/list/2447.html)

1. @Test
2. publicvoidtestInnerBeanInject(){
3. ApplicationContextcontext=
4. newClassPathXmlApplicationContext("chapter3/innerBeanInject.xml");
5. HelloApibean=context.getBean("bean",HelloApi.class);
6. bean.sayHello();
7. }

### 3.1.9 处理null值

Spring通过&lt;value&gt;标签或value属性注入常量值，所有注入的数据都是字符串，那如何注入null值呢？通过“null”值吗？当然不是因为如果注入“null”则认为是字符串。Spring通过&lt;null/&gt;标签注入null值。即可以采用如下配置方式：

![](http://sishuok.com/forum/upload/2012/2/20/b34ec2e56d4277b24bd81f826e56e1a2__20.JPG)

### 3.1.10 对象图导航注入支持

所谓对象图导航是指类似a.b.c这种点缀访问形式的访问或修改值。Spring支持对象图导航方式依赖注入。对象图导航依赖注入有一个限制就是比如a.b.c对象导航图注入中a和b必须为非null值才能注入c，否则将抛出空指针异常。

Spring不仅支持对象的导航，还支持数组、列表、字典、Properties数据类型的导航，对Set数据类型无法支持，因为无法导航。

数组和列表数据类型可以用array\[0]、list\[1]导航，注意”\[]”里的必须是数字，因为是按照索引进行导航，对于数组类型注意不要数组越界错误。

字典Map数据类型可以使用map\[1]、map\[str]进行导航，其中“\[]”里的是基本类型，无法放置引用类型。

让我们来练习一下吧。首先准备测试类，在此我们需要三个测试类，以便实现对象图导航功能演示：

NavigationC类用于打印测试代码，从而观察配置是否正确；具体类如下所示：

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2447.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2447.html)[打印](http://sishuok.com/forum/blogPost/list/2447.html)

1. packagecn.javass.spring.chapter3.bean;
2. publicclassNavigationC{
3. publicvoidsayNavigation(){
4. System.out.println("===navigationc");
5. }
6. }

NavigationB类，包含对象和列表、Properties、数组字典数据类型导航，而且这些复合数据类型保存的条目都是对象，正好练习一下如何往复合数据类型中注入对象依赖。具体类如下所示：

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2447.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2447.html)[打印](http://sishuok.com/forum/blogPost/list/2447.html)

01. packagecn.javass.spring.chapter3.bean;
02. importjava.util.List;
03. importjava.util.Map;
04. importjava.util.Properties;
05. publicclassNavigationB{
06. privateNavigationCnavigationC;
07. privateList&lt;NavigationC&gt;list;
08. privatePropertiesproperties;
09. privateNavigationC\[]array=newNavigationC\[1];
10. privateMap&lt;String,NavigationC&gt;map;
11. //由于setter和getter方法占用太多空间，故省略，大家自己实现吧
12. }

NavigationA类是我们的前端类，通过对它的导航进行注入值，具体代码如下：

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2447.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2447.html)[打印](http://sishuok.com/forum/blogPost/list/2447.html)

01. packagecn.javass.spring.chapter3.bean;
02. publicclassNavigationA{
03. privateNavigationBnavigationB;
04. publicvoidsetNavigationB(NavigationBnavigationB){
05. this.navigationB=navigationB;
06. }
07. publicNavigationBgetNavigationB(){
08. returnnavigationB;
09. }
10. }

接下来该进行Bean定义配置（resources/chapter3/navigationBeanInject.xml）了，首先让我们配置一下需要被导航的数据，NavigationC和NavigationB类，其中配置NavigationB时注意要确保比如array字段不为空值，这就需要或者在代码中赋值如“NavigationC\[] array = new NavigationC\[1];”，或者通过配置文件注入如“&lt;list&gt;&lt;/list&gt;”注入一个不包含条目的列表。具体配置如下：

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2447.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2447.html)[打印](http://sishuok.com/forum/blogPost/list/2447.html)

1. &lt;beanid="c"class="cn.javass.spring.chapter3.bean.NavigationC"/&gt;
2. &lt;beanid="b"class="cn.javass.spring.chapter3.bean.NavigationB"&gt;
3. &lt;propertyname="list"&gt;&lt;list&gt;&lt;/list&gt;&lt;/property&gt;
4. &lt;propertyname="map"&gt;&lt;map&gt;&lt;/map&gt;&lt;/property&gt;
5. &lt;propertyname="properties"&gt;&lt;props&gt;&lt;/props&gt;&lt;/property&gt;
6. &lt;/bean&gt;

配置完需要被导航的Bean定义了，该来配置NavigationA导航Bean了，在此需要注意，由于“navigationB”属性为空值，在此需要首先注入“navigationB”值；还有对于数组导航不能越界否则报错；具体配置如下：

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2447.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2447.html)[打印](http://sishuok.com/forum/blogPost/list/2447.html)

01. &lt;beanid="a"class="cn.javass.spring.chapter3.bean.NavigationA"&gt;
02. &lt;!--首先注入navigatiionB确保它非空--&gt;
03. &lt;propertyname="navigationB"ref="b"/&gt;
04. &lt;!--对象图导航注入--&gt;
05. &lt;propertyname="navigationB.navigationC"ref="c"/&gt;
06. &lt;!--注入列表数据类型数据--&gt;
07. &lt;propertyname="navigationB.list\[0]"ref="c"/&gt;
08. &lt;!--注入map类型数据--&gt;
09. &lt;propertyname="navigationB.map\[key]"ref="c"/&gt;
10. &lt;!--注入properties类型数据--&gt;
11. &lt;propertyname="navigationB.properties\[0]"ref="c"/&gt;
12. &lt;!--注入properties类型数据--&gt;
13. &lt;propertyname="navigationB.properties\[1]"ref="c"/&gt;
14. &lt;!--注入数组类型数据，注意不要越界--&gt;
15. &lt;propertyname="navigationB.array\[0]"ref="c"/&gt;
16. &lt;/bean&gt;

配置完毕，具体测试代码在cn.javass.spring.chapter3. DependencyInjectTest，让我们看下测试代码吧：

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2447.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2447.html)[打印](http://sishuok.com/forum/blogPost/list/2447.html)

01. //对象图导航
02. @Test
03. publicvoidtestNavigationBeanInject(){
04. ApplicationContextcontext=
05. newClassPathXmlApplicationContext("chapter3/navigationBeanInject.xml");
06. NavigationAnavigationA=context.getBean("a",NavigationA.class);
07. navigationA.getNavigationB().getNavigationC().sayNavigation();
08. navigationA.getNavigationB().getList().get(0).sayNavigation();
09. navigationA.getNavigationB().getMap().get("key").sayNavigation();
10. navigationA.getNavigationB().getArray()\[0].sayNavigation();
11. ((NavigationC)navigationA.getNavigationB().getProperties().get("1"))
12. .sayNavigation();
13. }

测试完毕，应该输出5个“===navigation c”，是不是很简单，注意这种方式是不推荐使用的，了解一下就够了，最好使用3.1.5一节使用的配置方式。

### 3.1.11配置简写

让我们来总结一下依赖注入配置及简写形式，其实我们已经在以上部分穿插着进行简化配置了：

一、构造器注入：

1）常量值

简写：&lt;constructor-arg index="0" value="常量"/&gt;

全写：&lt;constructor-arg index="0"&gt;&lt;value&gt;常量&lt;/value&gt;&lt;/constructor-arg&gt;

2）引用

简写：&lt;constructor-arg index="0" ref="引用"/&gt;

全写：&lt;constructor-arg index="0"&gt;&lt;ref bean="引用"/&gt;&lt;/constructor-arg&gt;

二、setter注入：

1）常量值

简写：&lt;property name="message" value="常量"/&gt;

全写：&lt;property name="message"&gt;&lt;value&gt;常量&lt;/value&gt;&lt;/ property&gt;

2）引用

简写：&lt;property name="message" ref="引用"/&gt;

全写：&lt;property name="message"&gt;&lt;ref bean="引用"/&gt;&lt;/ property&gt;

3）数组：&lt;array&gt;没有简写形式

4）列表：&lt;list&gt;没有简写形式

5）集合：&lt;set&gt;没有简写形式

6）字典

简写：&lt;map&gt;

&lt;entry key="键常量" value="值常量"/&gt;

&lt;entry key-ref="键引用" value-ref="值引用"/&gt;

&lt;/map&gt;

全写：&lt;map&gt;

&lt;entry&gt;&lt;key&gt;&lt;value&gt;键常量&lt;/value&gt;&lt;/key&gt;&lt;value&gt;值常量&lt;/value&gt;&lt;/entry&gt;

&lt;entry&gt;&lt;key&gt;&lt;ref bean="键引用"/&gt;&lt;/key&gt;&lt;ref bean="值引用"/&gt;&lt;/entry&gt;

&lt;/map&gt;

7）Properties：没有简写形式

三、使用p命名空间简化setter注入：

使用p命名空间来简化setter注入，具体使用如下：

java代码：

[查看](http://sishuok.com/forum/blogPost/list/2447.html)[复制到剪贴板](http://sishuok.com/forum/blogPost/list/2447.html)[打印](http://sishuok.com/forum/blogPost/list/2447.html)

01. &lt;?xmlversion="1.0"encoding="UTF-8"?&gt;
02. &lt;beansxmlns="http://www.springframework.org/schema/beans"
03. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
04. xmlns:p="http://www.springframework.org/schema/p"
05. xsi:schemaLocation="
06. http://www.springframework.org/schema/beans
07. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"&gt;
08. &lt;beanid="bean1"class="java.lang.String"&gt;
09. &lt;constructor-argindex="0"value="test"/&gt;
10. &lt;/bean&gt;
11. &lt;beanid="idrefBean1"class="cn.javass.spring.chapter3.bean.IdRefTestBean"
12. p:id="value"/&gt;
13. &lt;beanid="idrefBean2"class="cn.javass.spring.chapter3.bean.IdRefTestBean"
14. p:id-ref="bean1"/&gt;
15. &lt;/beans&gt;

<!--THE END-->

- xmlns:p="http://www.springframework.org/schema/p"：首先指定p命名空间；
- &lt;bean id="……" class="……" p:id="value"/&gt;：常量setter注入方式，其等价于&lt;property name="id" value="value"/&gt;；
  
  - - &lt;bean id="……" class="……" p:id-ref="bean1"/&gt;：引用setter注入方式，其等价于&lt;property name="id" ref="bean1"/&gt;。

原创内容，转载请注明【[http://sishuok.com/forum/posts/list/2447.html](http://sishuok.com/forum/posts/list/2447.html)】