---
title: "Spring IOC"
author: "AutomaticThoughts"
date: "2012-07-31T10:04:37Z"
tags: []
categories: ["企业架构"]
slug: "spring-ioc"
draft: false
lastmod: "2012-07-31T10:04:37Z"
id: 1613142
url: "https://automaticthoughts.iteye.com/blog/1613142"
---

转载自：[http://blog.csdn.net/it\_man/article/details/4402245](http://blog.csdn.net/it_man/article/details/4402245)

[http://chenguanwei2008.iteye.com/blog/361558](http://chenguanwei2008.iteye.com/blog/361558)

最近，买了本Spring入门书：spring In Action 。大致浏览了下感觉还不错。就是入门了点。Manning的书还是不错的，我虽然不像哪些只看Manning书的人那样专注于Manning,但怀着崇敬的心情和激情通览了一遍。又一次接受了IOC 、DI、AOP等Spring核心概念。 先就IOC和DI谈一点我的看法。

IOC（DI）：其实这个Spring架构核心的概念没有这么复杂，更不像有些书上描述的那样晦涩。java程序员都知道：java程序中的每个业务逻辑至少需要两个或以上的对象来协作完成，通常，每个对象在使用他的合作对象时，自己均要使用像new object（） 这样的语法来完成合作对象的申请工作。你会发现：对象间的耦合度高了。而IOC的思想是：Spring容器来实现这些相互依赖对象的创建、协调工作。对象只需要关系业务逻辑本身就可以了。从这方面来说，对象如何得到他的协作对象的责任被反转了（IOC、DI）。

这是我对Spring的IOC的体会。DI其实就是IOC的另外一种说法。DI是由Martin Fowler 在2004年初的一篇论文中首次提出的。他总结：控制的什么被反转了？就是：获得依赖对象的方式反转了。

如果对这一核心概念还不理解：这里引用一个叫Bromon的blog上找到的浅显易懂的答案：

IoC与DI

　　首先想说说IoC（Inversion of Control，控制倒转）。这是spring的核心，贯穿始终。所谓IoC，对于spring框架来说，就是由spring来负责控制对象的生命周期和对象间的关系。这是什么意思呢，举个简单的例子，我们是如何找女朋友的？常见的情况是，我们到处去看哪里有长得漂亮身材又好的mm，然后打听她们的兴趣爱好、qq号、电话号、ip号、iq号………，想办法认识她们，投其所好送其所要，然后嘿嘿……这个过程是复杂深奥的，我们必须自己设计和面对每个环节。传统的程序开发也是如此，在一个对象中，如果要使用另外的对象，就必须得到它（自己new一个，或者从JNDI中查询一个），使用完之后还要将对象销毁（比如Connection等），对象始终会和其他的接口或类藕合起来。

　　那么IoC是如何做的呢？有点像通过婚介找女朋友，在我和女朋友之间引入了一个第三者：婚姻介绍所。婚介管理了很多男男女女的资料，我可以向婚介提出一个列表，告诉它我想找个什么样的女朋友，比如长得像李嘉欣，身材像林熙雷，唱歌像周杰伦，速度像卡洛斯，技术像齐达内之类的，然后婚介就会按照我们的要求，提供一个mm，我们只需要去和她谈恋爱、结婚就行了。简单明了，如果婚介给我们的人选不符合要求，我们就会抛出异常。整个过程不再由我自己控制，而是有婚介这样一个类似容器的机构来控制。Spring所倡导的开发方式就是如此，所有的类都会在spring容器中登记，告诉spring你是个什么东西，你需要什么东西，然后spring会在系统运行到适当的时候，把你要的东西主动给你，同时也把你交给其他需要你的东西。所有的类的创建、销毁都由 spring来控制，也就是说控制对象生存周期的不再是引用它的对象，而是spring。对于某个具体的对象而言，以前是它控制其他对象，现在是所有对象都被spring控制，所以这叫控制反转。如果你还不明白的话，我决定放弃。

IoC的一个重点是在系统运行中，动态的向某个对象提供它所需要的其他对象。这一点是通过DI（Dependency Injection，依赖注入）来实现的。比如对象A需要操作数据库，以前我们总是要在A中自己编写代码来获得一个Connection对象，有了 spring我们就只需要告诉spring，A中需要一个Connection，至于这个Connection怎么构造，何时构造，A不需要知道。在系统运行时，spring会在适当的时候制造一个Connection，然后像打针一样，注射到A当中，这样就完成了对各个对象之间关系的控制。A需要依赖 Connection才能正常运行，而这个Connection是由spring注入到A中的，依赖注入的名字就这么来的。那么DI是如何实现的呢？ Java 1.3之后一个重要特征是反射（reflection），它允许程序在运行的时候动态的生成对象、执行对象的方法、改变对象的属性，spring就是通过反射来实现注入的。关于反射的相关资料请查阅java doc。  
　理解了IoC和DI的概念后，一切都将变得简单明了，剩下的工作只是在spring的框架中堆积木而已。

如果还不明白，放弃java吧！

 

**下面来让大家了解一下Spring到底是怎么运行的。**

Java代码[](http://www.javaeye.com/topic/413449 "复制代码")

1. public static void main(String\[] args) {
2. ApplicationContext context = new FileSystemXmlApplicationContext(
3. "applicationContext.xml");
4. Animal animal = (Animal) context.getBean("animal");
5. animal.say();
6. }

**\[java]** [view plain](http://automaticthoughts.iteye.com/admin/blogs/ "view plain")[copy](http://automaticthoughts.iteye.com/admin/blogs/ "copy")[print](http://automaticthoughts.iteye.com/admin/blogs/ "print")[?](http://automaticthoughts.iteye.com/admin/blogs/ "?")

1. public static void main(String\[] args) {
2. ApplicationContext context = new FileSystemXmlApplicationContext(
3. "applicationContext.xml");
4. Animal animal = (Animal) context.getBean("animal");
5. animal.say();
6. }

```
public static void main(String[] args) {
		ApplicationContext context = new FileSystemXmlApplicationContext(
				"applicationContext.xml");
		Animal animal = (Animal) context.getBean("animal");
		animal.say();
	}
```

这段代码你一定很熟悉吧，不过还是让我们分析一下它吧，首先是applicationContext.xml

Java代码[](http://www.javaeye.com/topic/413449 "复制代码")

1. &lt;bean id="animal" class="phz.springframework.test.Cat"&gt;
2. &lt;property name="name" value="kitty" /&gt;
3. &lt;/bean&gt;

**\[java]** [view plain](http://automaticthoughts.iteye.com/admin/blogs/ "view plain")[copy](http://automaticthoughts.iteye.com/admin/blogs/ "copy")[print](http://automaticthoughts.iteye.com/admin/blogs/ "print")[?](http://automaticthoughts.iteye.com/admin/blogs/ "?")

1. &lt;bean id="animal" class="phz.springframework.test.Cat"&gt;
2. &lt;property name="name" value="kitty" /&gt;
3. &lt;/bean&gt;

```
<bean id="animal" class="phz.springframework.test.Cat">
		<property name="name" value="kitty" />
	</bean>
```

他有一个类phz.springframework.test.Cat

Java代码[](http://www.javaeye.com/topic/413449 "复制代码")

1. public class Cat implements Animal {
2. private String name;
3. public void say() {
4. System.out.println("I am " + name + "!");
5. }
6. public void setName(String name) {
7. this.name = name;
8. }
9. }

**\[java]** [view plain](http://automaticthoughts.iteye.com/admin/blogs/ "view plain")[copy](http://automaticthoughts.iteye.com/admin/blogs/ "copy")[print](http://automaticthoughts.iteye.com/admin/blogs/ "print")[?](http://automaticthoughts.iteye.com/admin/blogs/ "?")

1. public class Cat implements Animal {
2. private String name;
3. public void say() {
4. System.out.println("I am " + name + "!");
5. }
6. public void setName(String name) {
7. this.name = name;
8. }
9. }

```
public class Cat implements Animal {
	private String name;
	public void say() {
		System.out.println("I am " + name + "!");
	}
	public void setName(String name) {
		this.name = name;
	}
}
```

实现了phz.springframework.test.Animal接口

Java代码[](http://www.javaeye.com/topic/413449 "复制代码")

1. public interface Animal {
2. public void say();
3. }

**\[java]** [view plain](http://automaticthoughts.iteye.com/admin/blogs/ "view plain")[copy](http://automaticthoughts.iteye.com/admin/blogs/ "copy")[print](http://automaticthoughts.iteye.com/admin/blogs/ "print")[?](http://automaticthoughts.iteye.com/admin/blogs/ "?")

1. public interface Animal {
2. public void say();
3. }

```
public interface Animal {
	public void say();
}
```

很明显上面的代码输出I am kitty!

那么到底Spring是如何做到的呢？  
接下来就让我们自己写个Spring 来看看Spring 到底是怎么运行的吧！

首先，我们定义一个Bean类，这个类用来存放一个Bean拥有的属性

Java代码[](http://www.javaeye.com/topic/413449 "复制代码")

1. /* Bean Id \*/
2. private String id;
3. /* Bean Class \*/
4. private String type;
5. /* Bean Property \*/
6. private Map&lt;String, Object&gt; properties = new HashMap&lt;String, Object&gt;();

**\[java]** [view plain](http://automaticthoughts.iteye.com/admin/blogs/ "view plain")[copy](http://automaticthoughts.iteye.com/admin/blogs/ "copy")[print](http://automaticthoughts.iteye.com/admin/blogs/ "print")[?](http://automaticthoughts.iteye.com/admin/blogs/ "?")

1. /* Bean Id \*/
2. private String id;
3. /* Bean Class \*/
4. private String type;
5. /* Bean Property \*/
6. private Map&lt;String, Object&gt; properties = new HashMap&lt;String, Object&gt;();

```
/* Bean Id */
	private String id;
	/* Bean Class */
	private String type;
	/* Bean Property */
	private Map<String, Object> properties = new HashMap<String, Object>();
```

一个Bean包括id,type,和Properties。

接下来Spring 就开始加载我们的配置文件了，将我们配置的信息保存在一个HashMap中，HashMap的key就是Bean 的 Id ，HasMap 的value是这个Bean，只有这样我们才能通过context.getBean("animal")这个方法获得Animal这个类。我们都知道Spirng可以注入基本类型，而且可以注入像List，Map这样的类型，接下来就让我们以Map为例看看Spring是怎么保存的吧

Map配置可以像下面的

Java代码[](http://www.javaeye.com/topic/413449 "复制代码")

01. &lt;bean id="test" class="Test"&gt;
02. &lt;property name="testMap"&gt;
03. &lt;map&gt;
04. &lt;entry key="a"&gt;
05. &lt;value&gt;1&lt;/value&gt;
06. &lt;/entry&gt;
07. &lt;entry key="b"&gt;
08. &lt;value&gt;2&lt;/value&gt;
09. &lt;/entry&gt;
10. &lt;/map&gt;
11. &lt;/property&gt;
12. &lt;/bean&gt;

**\[java]** [view plain](http://automaticthoughts.iteye.com/admin/blogs/ "view plain")[copy](http://automaticthoughts.iteye.com/admin/blogs/ "copy")[print](http://automaticthoughts.iteye.com/admin/blogs/ "print")[?](http://automaticthoughts.iteye.com/admin/blogs/ "?")

01. &lt;bean id="test" class="Test"&gt;
02. &lt;property name="testMap"&gt;
03. &lt;map&gt;
04. &lt;entry key="a"&gt;
05. &lt;value&gt;1&lt;/value&gt;
06. &lt;/entry&gt;
07. &lt;entry key="b"&gt;
08. &lt;value&gt;2&lt;/value&gt;
09. &lt;/entry&gt;
10. &lt;/map&gt;
11. &lt;/property&gt;
12. &lt;/bean&gt;

```
<bean id="test" class="Test">
		<property name="testMap">
			<map>
				<entry key="a">
					<value>1</value>
				</entry>
				<entry key="b">
					<value>2</value>
				</entry>
			</map>
		</property>
	</bean>
```

Spring是怎样保存上面的配置呢？，代码如下：

Java代码[](http://www.javaeye.com/topic/413449 "复制代码")

01. if (beanProperty.element("map") != null) {
02. Map&lt;String, Object&gt; propertiesMap = new HashMap&lt;String, Object&gt;();
03. Element propertiesListMap = (Element) beanProperty
04. .elements().get(0);
05. Iterator&lt;?&gt; propertiesIterator = propertiesListMap
06. .elements().iterator();
07. while (propertiesIterator.hasNext()) {
08. Element vet = (Element) propertiesIterator.next();
09. if (vet.getName().equals("entry")) {
10. String key = vet.attributeValue("key");
11. Iterator&lt;?&gt; valuesIterator = vet.elements()
12. .iterator();
13. while (valuesIterator.hasNext()) {
14. Element value = (Element) valuesIterator.next();
15. if (value.getName().equals("value")) {
16. propertiesMap.put(key, value.getText());
17. }
18. if (value.getName().equals("ref")) {
19. propertiesMap.put(key, new String\[] { value
20. .attributeValue("bean") });
21. }
22. }
23. }
24. }
25. bean.getProperties().put(name, propertiesMap);
26. }

**\[java]** [view plain](http://automaticthoughts.iteye.com/admin/blogs/ "view plain")[copy](http://automaticthoughts.iteye.com/admin/blogs/ "copy")[print](http://automaticthoughts.iteye.com/admin/blogs/ "print")[?](http://automaticthoughts.iteye.com/admin/blogs/ "?")

01. if (beanProperty.element("map") != null) {
02. Map&lt;String, Object&gt; propertiesMap = new HashMap&lt;String, Object&gt;();
03. Element propertiesListMap = (Element) beanProperty
04. .elements().get(0);
05. Iterator&lt;?&gt; propertiesIterator = propertiesListMap
06. .elements().iterator();
07. while (propertiesIterator.hasNext()) {
08. Element vet = (Element) propertiesIterator.next();
09. if (vet.getName().equals("entry")) {
10. String key = vet.attributeValue("key");
11. Iterator&lt;?&gt; valuesIterator = vet.elements()
12. .iterator();
13. while (valuesIterator.hasNext()) {
14. Element value = (Element) valuesIterator.next();
15. if (value.getName().equals("value")) {
16. propertiesMap.put(key, value.getText());
17. }
18. if (value.getName().equals("ref")) {
19. propertiesMap.put(key, new String\[] { value
20. .attributeValue("bean") });
21. }
22. }
23. }
24. }
25. bean.getProperties().put(name, propertiesMap);
26. }

```
if (beanProperty.element("map") != null) {
					Map<String, Object> propertiesMap = new HashMap<String, Object>();
					Element propertiesListMap = (Element) beanProperty
							.elements().get(0);
					Iterator<?> propertiesIterator = propertiesListMap
							.elements().iterator();
					while (propertiesIterator.hasNext()) {
						Element vet = (Element) propertiesIterator.next();
						if (vet.getName().equals("entry")) {
							String key = vet.attributeValue("key");
							Iterator<?> valuesIterator = vet.elements()
									.iterator();
							while (valuesIterator.hasNext()) {
								Element value = (Element) valuesIterator.next();
								if (value.getName().equals("value")) {
									propertiesMap.put(key, value.getText());
								}
								if (value.getName().equals("ref")) {
									propertiesMap.put(key, new String[] { value
											.attributeValue("bean") });
								}
							}
						}
					}
					bean.getProperties().put(name, propertiesMap);
				}
```

接下来就进入最核心部分了，让我们看看Spring 到底是怎么依赖注入的吧，其实依赖注入的思想也很简单，它是通过反射机制实现的，在实例化一个类时，它通过反射调用类中set方法将事先保存在HashMap中的类属性注入到类中。让我们看看具体它是怎么做的吧。  
首先实例化一个类，像这样

Java代码[](http://www.javaeye.com/topic/413449 "复制代码")

01. public static Object newInstance(String className) {
02. Class&lt;?&gt; cls = null;
03. Object obj = null;
04. try {
05. cls = Class.forName(className);
06. obj = cls.newInstance();
07. } catch (ClassNotFoundException e) {
08. throw new RuntimeException(e);
09. } catch (InstantiationException e) {
10. throw new RuntimeException(e);
11. } catch (IllegalAccessException e) {
12. throw new RuntimeException(e);
13. }
14. return obj;
15. }

**\[java]** [view plain](http://automaticthoughts.iteye.com/admin/blogs/ "view plain")[copy](http://automaticthoughts.iteye.com/admin/blogs/ "copy")[print](http://automaticthoughts.iteye.com/admin/blogs/ "print")[?](http://automaticthoughts.iteye.com/admin/blogs/ "?")

01. public static Object newInstance(String className) {
02. Class&lt;?&gt; cls = null;
03. Object obj = null;
04. try {
05. cls = Class.forName(className);
06. obj = cls.newInstance();
07. } catch (ClassNotFoundException e) {
08. throw new RuntimeException(e);
09. } catch (InstantiationException e) {
10. throw new RuntimeException(e);
11. } catch (IllegalAccessException e) {
12. throw new RuntimeException(e);
13. }
14. return obj;
15. }

```
public static Object newInstance(String className) {
		Class<?> cls = null;
		Object obj = null;
		try {
			cls = Class.forName(className);
			obj = cls.newInstance();
		} catch (ClassNotFoundException e) {
			throw new RuntimeException(e);
		} catch (InstantiationException e) {
			throw new RuntimeException(e);
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		}
		return obj;
	}
```

接着它将这个类的依赖注入进去，像这样

Java代码[](http://www.javaeye.com/topic/413449 "复制代码")

01. public static void setProperty(Object obj, String name, String value) {
02. Class&lt;? extends Object&gt; clazz = obj.getClass();
03. try {
04. String methodName = returnSetMthodName(name);
05. Method\[] ms = clazz.getMethods();
06. for (Method m : ms) {
07. if (m.getName().equals(methodName)) {
08. if (m.getParameterTypes().length == 1) {
09. Class&lt;?&gt; clazzParameterType = m.getParameterTypes()\[0];
10. setFieldValue(clazzParameterType.getName(), value, m,
11. obj);
12. break;
13. }
14. }
15. }
16. } catch (SecurityException e) {
17. throw new RuntimeException(e);
18. } catch (IllegalArgumentException e) {
19. throw new RuntimeException(e);
20. } catch (IllegalAccessException e) {
21. throw new RuntimeException(e);
22. } catch (InvocationTargetException e) {
23. throw new RuntimeException(e);
24. }
25. }

**\[java]** [view plain](http://automaticthoughts.iteye.com/admin/blogs/ "view plain")[copy](http://automaticthoughts.iteye.com/admin/blogs/ "copy")[print](http://automaticthoughts.iteye.com/admin/blogs/ "print")[?](http://automaticthoughts.iteye.com/admin/blogs/ "?")

01. public static void setProperty(Object obj, String name, String value) {
02. Class&lt;? extends Object&gt; clazz = obj.getClass();
03. try {
04. String methodName = returnSetMthodName(name);
05. Method\[] ms = clazz.getMethods();
06. for (Method m : ms) {
07. if (m.getName().equals(methodName)) {
08. if (m.getParameterTypes().length == 1) {
09. Class&lt;?&gt; clazzParameterType = m.getParameterTypes()\[0];
10. setFieldValue(clazzParameterType.getName(), value, m,
11. obj);
12. break;
13. }
14. }
15. }
16. } catch (SecurityException e) {
17. throw new RuntimeException(e);
18. } catch (IllegalArgumentException e) {
19. throw new RuntimeException(e);
20. } catch (IllegalAccessException e) {
21. throw new RuntimeException(e);
22. } catch (InvocationTargetException e) {
23. throw new RuntimeException(e);
24. }
25. }

```
public static void setProperty(Object obj, String name, String value) {
		Class<? extends Object> clazz = obj.getClass();
		try {
			String methodName = returnSetMthodName(name);
			Method[] ms = clazz.getMethods();
			for (Method m : ms) {
				if (m.getName().equals(methodName)) {
					if (m.getParameterTypes().length == 1) {
						Class<?> clazzParameterType = m.getParameterTypes()[0];
						setFieldValue(clazzParameterType.getName(), value, m,
								obj);
						break;
					}
				}
			}
		} catch (SecurityException e) {
			throw new RuntimeException(e);
		} catch (IllegalArgumentException e) {
			throw new RuntimeException(e);
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		} catch (InvocationTargetException e) {
			throw new RuntimeException(e);
		}
}
```

最后它将这个类的实例返回给我们，我们就可以用了。我们还是以Map为例看看它是怎么做的，我写的代码里面是创建一个HashMap并把该HashMap注入到需要注入的类中，像这样，

Java代码[](http://www.javaeye.com/topic/413449 "复制代码")

01. if (value instanceof Map) {
02. Iterator&lt;?&gt; entryIterator = ((Map&lt;?, ?&gt;) value).entrySet()
03. .iterator();
04. Map&lt;String, Object&gt; map = new HashMap&lt;String, Object&gt;();
05. while (entryIterator.hasNext()) {
06. Entry&lt;?, ?&gt; entryMap = (Entry&lt;?, ?&gt;) entryIterator.next();
07. if (entryMap.getValue() instanceof String\[]) {
08. map.put((String) entryMap.getKey(),
09. getBean(((String\[]) entryMap.getValue())\[0]));
10. }
11. }
12. BeanProcesser.setProperty(obj, property, map);
13. }

**\[java]** [view plain](http://automaticthoughts.iteye.com/admin/blogs/ "view plain")[copy](http://automaticthoughts.iteye.com/admin/blogs/ "copy")[print](http://automaticthoughts.iteye.com/admin/blogs/ "print")[?](http://automaticthoughts.iteye.com/admin/blogs/ "?")

01. if (value instanceof Map) {
02. Iterator&lt;?&gt; entryIterator = ((Map&lt;?, ?&gt;) value).entrySet()
03. .iterator();
04. Map&lt;String, Object&gt; map = new HashMap&lt;String, Object&gt;();
05. while (entryIterator.hasNext()) {
06. Entry&lt;?, ?&gt; entryMap = (Entry&lt;?, ?&gt;) entryIterator.next();
07. if (entryMap.getValue() instanceof String\[]) {
08. map.put((String) entryMap.getKey(),
09. getBean(((String\[]) entryMap.getValue())\[0]));
10. }
11. }
12. BeanProcesser.setProperty(obj, property, map);
13. }

```
if (value instanceof Map) {
				Iterator<?> entryIterator = ((Map<?, ?>) value).entrySet()
						.iterator();
				Map<String, Object> map = new HashMap<String, Object>();
				while (entryIterator.hasNext()) {
					Entry<?, ?> entryMap = (Entry<?, ?>) entryIterator.next();
					if (entryMap.getValue() instanceof String[]) {
						map.put((String) entryMap.getKey(),
								getBean(((String[]) entryMap.getValue())[0]));
					}
				}
				BeanProcesser.setProperty(obj, property, map);
			}
```

好了，这样我们就可以用Spring 给我们创建的类了，是不是也不是很难啊？当然Spring能做到的远不止这些，这个示例程序仅仅提供了Spring最核心的依赖注入功能中的一部分。  
本文参考了大量文章无法一一感谢，在这一起感谢，如果侵犯了你的版权深表歉意，很希望对大家有帮助！

 

 

 

 

IOC（Inversion of Control），即控制反转，它使你不需要再自己来实现对象的创建，而是把这些工作都交由容器来进行管理，增加了代码的可重用性。下面，便手动实现一个简单的IOC容器。

首先建立一个接口和这个接口的2个实现类：

 

Java代码 [![复制代码](http://automaticthoughts.iteye.com/images/icon_copy.gif)](http://automaticthoughts.iteye.com/admin/blogs/ "复制代码") [![收藏代码](http://automaticthoughts.iteye.com/images/icon_star.png)![](http://automaticthoughts.iteye.com/images/spinner.gif)]()

1. package cn.cgw.ioc;
2. public interface ReportGenerator {
3. public void generate(String\[]\[] table);
4. }

```
package cn.cgw.ioc;
public interface ReportGenerator {
	
	public void generate(String[][] table);
}

```

 

Java代码 [![复制代码](http://automaticthoughts.iteye.com/images/icon_copy.gif)](http://automaticthoughts.iteye.com/admin/blogs/ "复制代码") [![收藏代码](http://automaticthoughts.iteye.com/images/icon_star.png)![](http://automaticthoughts.iteye.com/images/spinner.gif)]()

1. &lt;SPAN style="WHITE-SPACE: normal"&gt;&lt;SPAN style="WHITE-SPACE: pre"&gt;package cn.cgw.ioc;&lt;/SPAN&gt;&lt;/SPAN&gt;
2. public class HtmlReportGenerator implements ReportGenerator {
3. public void generate(String\[]\[] table) {
4. System.out.println("Generate HTML report...............");
5. }
6. }

```
package cn.cgw.ioc;
public class HtmlReportGenerator implements ReportGenerator {

	public void generate(String[][] table) {
		System.out.println("Generate HTML report...............");
	}
}
```

 

Java代码 [![复制代码](http://automaticthoughts.iteye.com/images/icon_copy.gif)](http://automaticthoughts.iteye.com/admin/blogs/ "复制代码") [![收藏代码](http://automaticthoughts.iteye.com/images/icon_star.png)![](http://automaticthoughts.iteye.com/images/spinner.gif)]()

1. package cn.cgw.ioc;
2. public class PdfReportGenerator implements ReportGenerator {
3. public void generate(String\[]\[] table) {
4. System.out.println("Generate PDF report..................");
5. }
6. }

```
package cn.cgw.ioc;
public class PdfReportGenerator implements ReportGenerator {

	public void generate(String[][] table) {
		System.out.println("Generate PDF report..................");
	}
}
```

 

 

然后，我们建立一个名为ReportService的类，在这个类中需要到ReportGenerator接口的实现类对象，我们不再手工创建它，而是由IOC容器来管理，在这个类中采用setter方法进行注入。

 

Java代码 [![复制代码](http://automaticthoughts.iteye.com/images/icon_copy.gif)](http://automaticthoughts.iteye.com/admin/blogs/ "复制代码") [![收藏代码](http://automaticthoughts.iteye.com/images/icon_star.png)![](http://automaticthoughts.iteye.com/images/spinner.gif)]()

01. package cn.cgw.ioc;
02. public class ReportService {
03. private ReportGenerator reportGenerator;
04. /\**
05. * 采用setter注入
06. * @param reportGenerator
07. \*/
08. public void setReportGenerator(ReportGenerator reportGenerator) {
09. this.reportGenerator = reportGenerator;
10. }
11. public void generateAnnualReport(int year) {
12. String\[]\[] statistics = null;
13. //
14. // Gather statistics for the year ...
15. //
16. reportGenerator.generate(statistics);
17. }
18. public void generateMonthlyReport(int year, int month) {
19. String\[]\[] statistics = null;
20. //
21. // Gather statistics for the month ...
22. //
23. reportGenerator.generate(statistics);
24. }
25. public void generateDailyReport(int year, int month, int day) {
26. String\[]\[] statistics = null;
27. //
28. // Gather statistics for the day ...
29. //
30. reportGenerator.generate(statistics);
31. }
32. }

```
package cn.cgw.ioc;

public class ReportService {

	private ReportGenerator reportGenerator;
	
	/**
	 * 采用setter注入
	 * @param reportGenerator
	 */
	public void setReportGenerator(ReportGenerator reportGenerator) {
		this.reportGenerator = reportGenerator;
	}
	
	public void generateAnnualReport(int year) {
        String[][] statistics = null;
        //
        // Gather statistics for the year ...
        //
        reportGenerator.generate(statistics);
    }

    public void generateMonthlyReport(int year, int month) {
        String[][] statistics = null;
        //
        // Gather statistics for the month ...
        //
        reportGenerator.generate(statistics);
    }

    public void generateDailyReport(int year, int month, int day) {
        String[][] statistics = null;
        //
        // Gather statistics for the day ...
        //
        reportGenerator.generate(statistics);
    }
}

```

 

 下面我们建立一个属性文件，在属性文件中，定义了属性与对应类的映射关系：

 

Java代码 [![复制代码](http://automaticthoughts.iteye.com/images/icon_copy.gif)](http://automaticthoughts.iteye.com/admin/blogs/ "复制代码") [![收藏代码](http://automaticthoughts.iteye.com/images/icon_star.png)![](http://automaticthoughts.iteye.com/images/spinner.gif)]()

1. # Define a new component "reportGenerator"
2. reportGenerator=cn.cgw.ioc.HtmlReportGenerator
3. # Define a new component "reportService"
4. reportService=cn.cgw.ioc.ReportService
5. # Inject the component "reportGenerator" into property "reportGenerator"
6. reportService.reportGenerator=reportGenerator

```
# Define a new component "reportGenerator"
reportGenerator=cn.cgw.ioc.HtmlReportGenerator

# Define a new component "reportService"
reportService=cn.cgw.ioc.ReportService
# Inject the component "reportGenerator" into property "reportGenerator"
reportService.reportGenerator=reportGenerator
```

 

 然后，我们实现IOC容器，在这个类中需要用到Apache的两个jar包。分别是common-logging和common-beanutils

 

Java代码 [![复制代码](http://automaticthoughts.iteye.com/images/icon_copy.gif)](http://automaticthoughts.iteye.com/admin/blogs/ "复制代码") [![收藏代码](http://automaticthoughts.iteye.com/images/icon_star.png)![](http://automaticthoughts.iteye.com/images/spinner.gif)]()

01. package cn.cgw.ioc;
02. import java.io.FileInputStream;
03. import java.io.FileNotFoundException;
04. import java.io.IOException;
05. import java.io.InputStream;
06. import java.util.HashMap;
07. import java.util.Map;
08. import java.util.Properties;
09. import org.apache.commons.beanutils.PropertyUtils;
10. public class Container {
11. private Map&lt;String,Object&gt; components;
12. public Container() {
13. components = new HashMap&lt;String,Object&gt;();
14. try {
15. Properties properties = new Properties();
16. //load properties file
17. InputStream istr = this.getClass().getResourceAsStream("components.properties");
18. properties.load(istr);
19. for(Map.Entry entry : properties.entrySet()) {
20. String key = (String)entry.getKey();
21. String value = (String)entry.getValue();
22. processEntry(key,value);
23. }
24. } catch (FileNotFoundException e) {
25. e.printStackTrace();
26. } catch (IOException e) {
27. e.printStackTrace();
28. } catch (Exception e) {
29. e.printStackTrace();
30. }
31. }
32. private void processEntry(String key, String value) throws Exception{
33. String\[] parts = key.split("\\\\.");
34. //new component definition
35. if(parts.length == 1) {
36. //reflection
37. Object component = Class.forName(value).newInstance();
38. components.put(parts\[0], component);
39. } else {
40. // Dependency injection
41. Object component = components.get(parts\[0]);
42. Object reference = components.get(value);
43. PropertyUtils.setProperty(component,parts\[1],reference);
44. }
45. }
46. public Object getComponent(String id) {
47. return components.get(id);
48. }
49. }

```
package cn.cgw.ioc;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.beanutils.PropertyUtils;

public class Container {
	
	private Map<String,Object> components;

	public Container() {
		
		components = new HashMap<String,Object>();
		
		try {
			Properties properties = new Properties();
			//load properties file
			InputStream istr = this.getClass().getResourceAsStream("components.properties");
			properties.load(istr);
			
			for(Map.Entry entry : properties.entrySet()) {
				String key = (String)entry.getKey();
				String value = (String)entry.getValue();
				processEntry(key,value);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void processEntry(String key, String value) throws Exception{
		String[] parts = key.split("\\.");
		//new component definition
		if(parts.length == 1) {
			//reflection
			Object component = Class.forName(value).newInstance();
			components.put(parts[0], component);
		} else {
			// Dependency injection
			Object component = components.get(parts[0]);
			Object reference = components.get(value);
			PropertyUtils.setProperty(component,parts[1],reference);
		}	
	}
	
	public Object getComponent(String id) {
		return components.get(id);
	}
}

```

 

 这样我们的工作就完成了，最后再写个测试方法来检验代码的正确性：

 

Java代码 [![复制代码](http://automaticthoughts.iteye.com/images/icon_copy.gif)](http://automaticthoughts.iteye.com/admin/blogs/ "复制代码") [![收藏代码](http://automaticthoughts.iteye.com/images/icon_star.png)![](http://automaticthoughts.iteye.com/images/spinner.gif)]()

1. Container container = new Container();
2. ReportService reportService = (ReportService)container.getComponent("reportService");
3. reportService.generateAnnualReport(2009);

```
Container container = new Container();
ReportService reportService = (ReportService)container.getComponent("reportService");
reportService.generateAnnualReport(2009);
```

 

 可以看到，输出的结果为：

 Generate HTML report...............

 如果，我们将属性文件中reportGenerator=的值改为PdfReportGenerator，则输出的结果为：

 Generate PDF report...............

 

通过以上结果我们可以清楚地认识到IOC的特性，我们并没有在ReportService类中创建ReportGenerator的任何实现类对象，这一切都是交由IOC容器进行管理的，通过属性文件的配置，我们可以轻松地更改想要使用的ReportGenerator实现类对象，它大大提高了代码的复用性。