---
title: "编码剖析Spring依赖注入的原理"
author: "freewxy"
date: "2011-08-10T20:01:21Z"
tags: []
categories: ["编程语言"]
slug: "spring"
draft: false
lastmod: "2011-08-10T20:01:21Z"
id: 1145040
url: "https://freewxy.iteye.com/blog/1145040"
---

**一、注入依赖对象**

基本类型对象注入：

```
<bean id=”orderService” class=”com.wxy.service.OrderServiceBean”>

   <constructor-arg index=”0” type=”java.lang.String” value=”xxx”/>//构造器注入

   <property name=”name” value=”wxy”/>//属性setter方法注入

</bean>

```

```

```

```

```

注入其他bean:

 方式一：

```
<bean id=”orderDao” class=”com.wxy.service.OrderDaoBean”/>

<bean id=”orderService” class=”com.wxy.service.OrderServiceBean”>

<property name=”orderDao” ref=”orderDao”/>

 </bean>
```

 

 

方法二：（使用内部bean，但该bean不能被其他bean使用）

```
<bean id=”orderService” class=”com.wxy.service.OrderServiceBean”>

      <property name=”orderDao”>

           <bean class=”com.wxy.service.OrderDaoBean”/>

      </property>

</bean>
```

 

 

 

**二、依赖注入（Dependency Injection）**

所谓依赖注入就是指：在运行期，由外部容器动态的将依赖对象注入到组件中。

 

 

**三、编码实现依赖注入功能：**

1、 修改beans.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"

       xsi:schemaLocation="http://www.springframework.org/schema/beans

           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

         <bean id="peopleDao" class="com.wxy.dao.impl.PeopleDaoBean"></bean>

         <bean id="peopleService" class="com.wxy.service.impl.PeopleServiceBean">

         <property name="peopleDap" ref="peopleDao"></property>

         <property name="xx" ref="xxDao"></property>

         </bean>

</beans>
```

 1.1

 

 

创建dao类：

```
package com.wxy.dao.impl;

import com.wxy.dao.PeopleDao;

/**

*   Dao类，实现数据的持久化操作 

*   @create-time     2011-8-10   下午07:25:26   

*   @revision          $Id

*/

public class PeopleDaoBean implements PeopleDao {


    /* (non-Javadoc)

     * @see com.wxy.dao.impl.PeopleDao#add()

     */

    public void add() {

        System.out.println("this is the method PeopleDaoBean.add()!");

    }

}
```

 

 

 

 

   1.2创建dao接口：

```
package com.wxy.dao;

public interface PeopleDao {

    public abstract void add();

}

```

 

 

 

 

2、新建PropertyDefinition类，存放bean的property属性：

```
package com.wxy.bean;

 

/**

*   存放bean的property属性 

*   @create-time     2011-8-10   下午04:40:07   

*   @revision          $Id

*/

public class PropertyDefinition {

    private String name; //属性名
   private String ref;  //属性依赖对象


    /**

     * @return the name

     */

    public String getName() {

        return name;

    }

    /**

     * @param name the name to set

     */

    public void setName(String name) {

        this.name = name;

    } 

    /**

     * @return the ref

     */

    public String getRef() {

        return ref;

    }

    /**

     * @param ref the ref to set

     */

    public void setRef(String ref) {

        this.ref = ref;

    }

    public PropertyDefinition(String name, String ref) {

        super();

        this.name = name;

        this.ref = ref;

    }

}
```

 

 

 

2.1、 在BeanDefinition中加入PropertyList属性，存放property列表

```
package com.wxy.bean;

 

import java.util.ArrayList;

import java.util.List;

 

public class BeanDefinition {

    private String                   id;

    private String                   className;

    private List<PropertyDefinition> properties = new       ArrayList<PropertyDefinition>(); //存放bean的属性列表 

    public BeanDefinition(String id, String className) {

        this.id = id;

        this.className = className;

    }


    /**

     * @return the id

     */

    public String getId() {

        return id;

    }


    /**

     * @param id the id to set

     */

    public void setId(String id) {

        this.id = id;

    }

    /**

     * @return the className

     */

    public String getClassName() {

        return className;

    }

    /**

     * @param className the className to set

     */

    public void setClassName(String className) {

        this.className = className;

}

/**

     * @return the properties

     */

    public List<PropertyDefinition> getProperties() {

        return properties;

    }

    /**

     * @param properties the properties to set

     */

    public void setProperties(List<PropertyDefinition> properties) {

        this.properties = properties;

    }
}
```

 

 

 

 

  2.2配置peopleServiceBean,实现注入功能：

```
package com.wxy.service.impl;

 

import com.wxy.dao.PeopleDao;

import com.wxy.service.PeopleService;

 

/**

*   PeopleServiceBean

*   @create-time     2011-8-9   下午11:07:03   

*   @revision          $Id:PeopleServiceBean.java

*/

public class PeopleServiceBean implements PeopleService {

    private PeopleDao peopleDao;

 
    /**

     * @return the peopleDao

     */

    public PeopleDao getPeopleDao() {

        return peopleDao;

    }

    public void save() {

        System.out.println("--> the method is called save()!");

        peopleDao.add();

    }

    /**

     * @param peopleDao the peopleDao to set

     */

    public void setPeopleDao(PeopleDao peopleDao) {

        this.peopleDao = peopleDao;

    }
}
```

 

 

 

 

3、进入WxyClassPathXMLApplicationContext中，自己编码实现依赖注入内部功能：

```
 package com.wxy.content;

 

import java.beans.IntrospectionException;

import java.beans.Introspector;

import java.beans.PropertyDescriptor;

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;

import java.net.URL;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

 

import org.dom4j.Document;

import org.dom4j.Element;

import org.dom4j.XPath;

import org.dom4j.io.SAXReader;

 

import com.wxy.bean.BeanDefinition;

import com.wxy.bean.PropertyDefinition;

 

/**

*  自定义IoC容器 

*  BeanDefinition的resource定位:readXML();

*  BeanDefinition的载入和解析 :readXML();

*  BeanDefinition在IoC容器中的注册 instanceBeans();

*   @create-time     2011-8-10   上午09:19:17   

*   @revision          $Id

*/

public class WxyClassPathXMLApplicationContext {

 

    //存放BeanDefinition的列表，在beans.xml中定义的bean可能不止一个

    private final List<BeanDefinition> beanDefines = new ArrayList<BeanDefinition>();

    //将类名作为索引，将创建的Bean对象存入到Map中

    private final Map<String, Object>  sigletons   = new HashMap<String, Object>();

 

    public WxyClassPathXMLApplicationContext(String fileName) {

        //读取xml配置文件

        this.readXML(fileName);

        //实例化bean

        this.instanceBeans();

        //注入对象

        this.injectObject();

    }

 

    /**

     * 注入对象方法

     */

    private void injectObject() {

        for (BeanDefinition beanDefinition : beanDefines) {

            //获取beanDefines中的对象

            Object bean = sigletons.get(beanDefinition.getId());

            if (bean != null) {

                //如果存在，利用反射技术将值注入

                try {

                    PropertyDescriptor[] ps = Introspector.getBeanInfo(bean.getClass())

                        .getPropertyDescriptors();

                    for (PropertyDefinition propertyDefinition : beanDefinition.getProperties()) {

                        for (PropertyDescriptor properdesc : ps) {

                            //取得属性名字与propertyDefinition中的属性做比较

                            if (propertyDefinition.getName().equals(properdesc.getName())) {

                                //获得属性的setter方法

                                Method setter = properdesc.getWriteMethod();

                                if (setter != null) {

                                    Object value = sigletons.get(propertyDefinition.getRef());

                                    //把引用对象注入到属性

                                    setter.setAccessible(true);//允许访私有方法

                                    setter.invoke(bean, value);

                                }

                            }

                        }

                    }

                } catch (SecurityException e) {

                    // TODO Auto-generated catch block

                    e.printStackTrace();

                } catch (IllegalArgumentException e) {

                    // TODO Auto-generated catch block

                    e.printStackTrace();

                } catch (IntrospectionException e) {

                    // TODO Auto-generated catch block

                    e.printStackTrace();

                } catch (IllegalAccessException e) {

                    // TODO Auto-generated catch block

                    e.printStackTrace();

                } catch (InvocationTargetException e) {

                    // TODO Auto-generated catch block

                    e.printStackTrace();

                }

            }

        }

    }

 

    /**

     * 读取XML配置文件，获取BeanDefinition内容，存入到beanDefinition列表中

     * @param fileName xml配置文件名称

     */

 

    private void readXML(String fileName) {

        SAXReader saxReader = new SAXReader();

        Document document = null;

        try {

            //通过类加载器获取Resource资源路径,实现BeanDefinition的resource定位

            URL xmlPath = this.getClass().getClassLoader().getResource(fileName);

            //将xml读入到document中

            document = saxReader.read(xmlPath);

            Map<String, String> nsMap = new HashMap<String, String>();

            //加入命名空间

            nsMap.put("ns", "http://www.springframework.org/schema/beans");

            //创建beans/bean查询路径,注意：路径前要注明命名空间，便于解析

            XPath xsub = document.createXPath("//ns:beans/ns:bean");

            //设置命名空间

            xsub.setNamespaceURIs(nsMap);

            //获取文档下的所有Bean节点

            List<Element> beans = xsub.selectNodes(document);

            for (Element element : beans) {

                //获取id属性值

                String id = element.attributeValue("id");

                //获取class属性值

                String clazz = element.attributeValue("class");

                BeanDefinition beanDefinition = new BeanDefinition(id, clazz);

                //创建bean/property查询路径

                XPath propertysub = element.createXPath("ns:property");

                //设置命名空间

                propertysub.setNamespaceURIs(nsMap);

                //获取bean的property列表节点

                List<Element> properties = propertysub.selectNodes(element);

                for (Element property : properties) {

                    String propertyName = property.attributeValue("name");

                    String propertyref = property.attributeValue("ref");

                    PropertyDefinition propertyDefinition = new PropertyDefinition(propertyName,

                        propertyref);

                    System.out.println(property);

                    //将property属性添加到beanDefinition中

                    beanDefinition.getProperties().add(propertyDefinition);

                }

                //将新创建的BeanDefinition赌侠ing放入到BeanDeifnitions中

                beanDefines.add(beanDefinition);

            }

        } catch (Exception e) {

            System.out.println(e.toString());

        }

    }

 

    /**

     * 实例化bean,存入到sigletons中

     */

    private void instanceBeans() {

        for (BeanDefinition beanDefinition : beanDefines) {

            try {

                if (beanDefinition.getClassName() != null

                    && !(beanDefinition.getClassName().isEmpty())) {

                    //利用java反射机制，生成BeanDefinition实例，并将其注册到sigletons中

                    sigletons.put(beanDefinition.getId(), Class.forName(

                        beanDefinition.getClassName()).newInstance());

                }

            } catch (Exception e) {

                e.printStackTrace();

            }

        }

 

    }

 

    /**

     * 根据ID名获取实例bean

     * return 返回一个Object对象，用户使用时，需要对获取的结果进行转换类型

     */

    public Object getBean(String beanName) {

        return this.sigletons.get(beanName);

    }

} 

```

 

 

 

  测试一下看是否取到了property的属性值：

```
public class Test {

 

    public static void main(String[] args) {

        //IOC容器实例化

        WxyClassPathXMLApplicationContext ac = new WxyClassPathXMLApplicationContext("beans.xml");

        PeopleService peopleService = (PeopleService) ac.getBean("peopleService");

        peopleService.save();

    }

}
```

 测试结果：

\---------------------------------------

--&gt; the method is called save()!  
this is the method PeopleDaoBean.add()!

\----------------------------------------