简单模拟Spring容器(一)(转)

 

简单模拟Spring容器(一)

标签: sspring
分类:

本次模拟非常简单,所以直接上代码!

一、配置文件bean.xml

 

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans>   
  3.     <bean id="com.summer.test.Test" class="com.summer.test.Test" name="com.summer.test.Test"></bean>  
  4. </beans>  

 

二、实体类Test

 

  1. package com.summer.test;  
  2. public class Test {  
  3.     public void test(){  
  4.         System.out.println("=======test=========");  
  5.     }  
  6. }  


三、模拟Spring容器SpringContext

 

    1. package com.summer.util;  
    2.   
    3. import java.util.HashMap;  
    4. import java.util.List;  
    5. import java.util.Map;  
    6.   
    7. import org.dom4j.Document;  
    8. import org.dom4j.DocumentException;  
    9. import org.dom4j.Element;  
    10. import org.dom4j.io.SAXReader;  
    11.   
    12. import com.summer.test.Test;  
    13.   
    14. /** 
    15.  * 自定义Spring容器 
    16.  * @author Administrator 
    17.  * 
    18.  */  
    19. public class SpringContext {  
    20.       
    21.     /** 
    22.      * key:为bean的属性ID的值 
    23.      * value:为bean的属性class的值 
    24.      */  
    25.     public static Map<String, Object> map = new HashMap<String, Object>();  
    26.       
    27.     /** 
    28.      * 读取配置文件,解析配置文件 
    29.      */  
    30.     public static void readApplicationContextXml(){  
    31.         try {  
    32.             SAXReader reader = new SAXReader();  
    33.             Document doc = reader.read("bean.xml");  
    34.             Element root = doc.getRootElement();  
    35.             List<Element> beans = root.elements();  
    36.             for (Element bean : beans) {  
    37.                 String id = bean.attributeValue("id");  
    38.                 String clazz = bean.attributeValue("class");  
    39.                 map.put(id, Class.forName(clazz).newInstance());  
    40.             }  
    41.         } catch (DocumentException e) {  
    42.             e.printStackTrace();  
    43.         } catch (ClassNotFoundException e) {  
    44.             e.printStackTrace();  
    45.         } catch (InstantiationException e) {  
    46.             e.printStackTrace();  
    47.         } catch (IllegalAccessException e) {  
    48.             e.printStackTrace();  
    49.         }  
    50.     }  
    51.       
    52.     public static Object getBean(String beanName){  
    53.         readApplicationContextXml();  
    54.         return map.get(beanName);  
    55.     }  
    56.   
    57.     /** 
    58.      * 测试 
    59.      * @param args 
    60.      */  
    61.     public static void main(String[] args) {  
    62.         Test test = (Test) SpringContext.getBean("com.summer.test.Test");  
    63.         test.test();  
    64.     }  

 

posted @ 2017-11-14 15:45  yasepix  阅读(118)  评论(0编辑  收藏  举报