Spring管理bean的原理自定义实现



1、Spring通过BeanDefinition管理基于Spring的应用中的各种对象以及他们之间的相互依赖关系。BeanDefinition抽象了我们对Bean的定义,是让容器起作用的主要数据类型。 IoC容器是用来管理对象依赖关系的,对IoC容器来说,BeanDefinition就是对依赖反转模式中管理的对象依赖关系的数据抽象,也是容器实现依赖反转功能的核心数据结构,依赖反转功能都是围绕对这个BeanDefinition的处理上完成的。

   定义BeanDefinition: 

 

Java代码 复制代码  收藏代码
  1. package com.wxy.bean;  
  2.   
  3. public class beanDefinition {  
  4.   
  5.    
  6.   
  7.     private String id;  
  8.   
  9.     private String className;  
  10.   
  11.    
  12.   
  13.     public beanDefinition(String id, String className) {  
  14.   
  15.         this.id = id;  
  16.   
  17.         this.className = className;  
  18.   
  19.     }  
  20.   
  21.    
  22.   
  23.     /** 
  24.  
  25.      * @return the id 
  26.  
  27.      */  
  28.   
  29.     public String getId() {  
  30.   
  31.         return id;  
  32.   
  33.     }  
  34.   
  35.    
  36.   
  37.     /** 
  38.  
  39.      * @param id the id to set 
  40.  
  41.      */  
  42.   
  43.     public void setId(String id) {  
  44.   
  45.         this.id = id;  
  46.   
  47.     }  
  48.   
  49.    
  50.   
  51.     /** 
  52.  
  53.      * @return the className 
  54.  
  55.      */  
  56.   
  57.     public String getClassName() {  
  58.   
  59.         return className;  
  60.   
  61.     }  
  62.   
  63.    
  64.   
  65.     /** 
  66.  
  67.      * @param className the className to set 
  68.  
  69.      */  
  70.   
  71.     public void setClassName(String className) {  
  72.   
  73.         this.className = className;  
  74.   
  75.     }  
  76.   
  77.    
  78.   
  79. }  
package com.wxy.bean;

public class beanDefinition {

 

    private String id;

    private String className;

 

    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;

    }

 

}

 

2、自定义IoC容器WxyClassPathXMLApplicationContext ,该容器实现三个功能:

 (1 BeanDefinitionresource定位:readXML();

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

 (3 BeanDefinitionIoC容器中的注册 instanceBeans();

Java代码 复制代码  收藏代码
  1. package com.wxy.content;  
  2.   
  3.    
  4.   
  5. import java.net.URL;  
  6.   
  7. import java.util.ArrayList;  
  8.   
  9. import java.util.HashMap;  
  10.   
  11. import java.util.List;  
  12.   
  13. import java.util.Map;  
  14.   
  15.    
  16.   
  17. import org.dom4j.Document;  
  18.   
  19. import org.dom4j.Element;  
  20.   
  21. import org.dom4j.XPath;  
  22.   
  23. import org.dom4j.io.SAXReader;  
  24.   
  25.    
  26.   
  27. import com.wxy.bean.BeanDefinition;  
  28.   
  29.    
  30.   
  31. /** 
  32.  
  33. *  自定义IoC容器  
  34.  
  35. *  BeanDefinition的resource定位:readXML(); 
  36.  
  37. *  BeanDefinition的载入和解析 :readXML(); 
  38.  
  39. *  BeanDefinition在IoC容器中的注册 instanceBeans(); 
  40.  
  41. *   @create-time     2011-8-10   上午09:19:17    
  42.  
  43. *   @revision          $Id 
  44.  
  45. */  
  46.   
  47. public class WxyClassPathXMLApplicationContext {  
  48.   
  49.    
  50.   
  51.     //存放BeanDefinition的列表,在beans.xml中定义的bean可能不止一个  
  52.   
  53.     private final List<BeanDefinition> beanDefinitions = new ArrayList<BeanDefinition>();  
  54.   
  55.     //将类名作为索引,将创建的Bean对象存入到Map中  
  56.   
  57.     private final Map<String, Object>  sigletons       = new HashMap<String, Object>();  
  58.   
  59.    
  60.   
  61.     public WxyClassPathXMLApplicationContext(String fileName) {  
  62.   
  63.         //读取xml配置文件  
  64.   
  65.         this.readXML(fileName);  
  66.   
  67.         //实例化bean  
  68.   
  69.         this.instanceBeans();  
  70.   
  71.     }  
  72.   
  73.    
  74.   
  75.     /** 
  76.  
  77.      * 读取XML配置文件,获取BeanDefinition内容,存入到beanDefinition列表中 
  78.  
  79.      * @param fileName xml配置文件名称 
  80.  
  81.      */  
  82.   
  83.    
  84.   
  85.     private void readXML(String fileName) {  
  86.   
  87.         SAXReader saxReader = new SAXReader();  
  88.   
  89.         Document document = null;  
  90.   
  91.         try {  
  92.   
  93.             //通过类加载器获取Resource资源路径,实现BeanDefinition的resource定位  
  94.   
  95.             URL xmlPath = this.getClass().getClassLoader().getResource(fileName);  
  96.   
  97.             //将xml读入到document中  
  98.   
  99.             document = saxReader.read(xmlPath);  
  100.   
  101.             Map<String, String> nsMap = new HashMap<String, String>();  
  102.   
  103.             //加入命名空间  
  104.   
  105.             nsMap.put("ns""http://www.springframework.org/schema/beans");  
  106.   
  107.             //创建beans/bean查询路径,注意:路径前要注明命名空间,便于解析  
  108.   
  109.             XPath xsub = document.createXPath("//ns:beans/ns:bean");  
  110.   
  111.             //设置命名空间  
  112.   
  113.             xsub.setNamespaceURIs(nsMap);  
  114.   
  115.             //获取文档下的所有Bean节点  
  116.   
  117.             List<Element> beans = xsub.selectNodes(document);  
  118.   
  119.             for (Element element : beans) {  
  120.   
  121.                 //获取id属性值  
  122.   
  123.                 String id = element.attributeValue("id");  
  124.   
  125.                 //获取class属性值  
  126.   
  127.                 String clazz = element.attributeValue("class");  
  128.   
  129.                 BeanDefinition beanDefinition = new BeanDefinition(id, clazz);  
  130.   
  131.                 //将新创建的BeanDefinition赌侠ing放入到BeanDeifnitions中  
  132.   
  133.                 beanDefinitions.add(beanDefinition);  
  134.   
  135.             }  
  136.   
  137.         } catch (Exception e) {  
  138.   
  139.             System.out.println(e.toString());  
  140.   
  141.         }  
  142.   
  143.     }  
  144.   
  145.    
  146.   
  147.     /** 
  148.  
  149.      * 实例化bean,存入到sigletons中 
  150.  
  151.      */  
  152.   
  153.     private void instanceBeans() {  
  154.   
  155.         for (BeanDefinition beanDefinition : beanDefinitions) {  
  156.   
  157.             try {  
  158.   
  159.                 if (beanDefinition.getClassName() != null  
  160.   
  161.                     && !(beanDefinition.getClassName().isEmpty())) {  
  162.   
  163.                     //利用java反射机制,生成BeanDefinition实例,并将其注册到sigletons中  
  164.   
  165.                     sigletons.put(beanDefinition.getId(), Class.forName(  
  166.   
  167.                         beanDefinition.getClassName()).newInstance());  
  168.   
  169.                 }  
  170.   
  171.             } catch (Exception e) {  
  172.   
  173.                 e.printStackTrace();  
  174.   
  175.             }  
  176.   
  177.         }  
  178.   
  179.    
  180.   
  181.     }  
  182.   
  183.    
  184.   
  185.     /** 
  186.  
  187.      * 根据ID名获取实例bean 
  188.  
  189.      * return 返回一个Object对象,用户使用时,需要对获取的结果进行转换类型 
  190.  
  191.      */  
  192.   
  193.     public Object getBean(String beanName) {  
  194.   
  195.         return this.sigletons.get(beanName);  
  196.   
  197.     }  
  198.   
  199. }  
package com.wxy.content;

 

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;

 

/**

*  自定义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> beanDefinitions = 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();

    }

 

    /**

     * 读取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);

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

                beanDefinitions.add(beanDefinition);

            }

        } catch (Exception e) {

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

        }

    }

 

    /**

     * 实例化bean,存入到sigletons中

     */

    private void instanceBeans() {

        for (BeanDefinition beanDefinition : beanDefinitions) {

            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);

    }

}

 

 

 

 

3、在测试类中使用自定义的IoC容器:

Java代码 复制代码  收藏代码
  1. public class Test {  
  2.   
  3.    
  4.   
  5.     public static void main(String[] args) {  
  6.   
  7.         //IOC容器实例化  
  8.   
  9.         WxyClassPathXMLApplicationContext ctx = new WxyClassPathXMLApplicationContext("beans.xml");  
  10.   
  11.         //获取业务bean  
  12.   
  13.         PeopleServiceBean peopleService = (PeopleServiceBean) ctx.getBean("peopleService");  
  14.   
  15.         peopleService.save();  
  16.   
  17.     }  
  18.   
  19.    
  20.   
  21. }  
public class Test {

 

    public static void main(String[] args) {

        //IOC容器实例化

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

        //获取业务bean

        PeopleServiceBean peopleService = (PeopleServiceBean) ctx.getBean("peopleService");

        peopleService.save();

    }

 

}

 

测试结果:

-----------------------------------------

--> the method is called save()!

-----------------------------------------

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值