编码剖析Spring管理bean的原理

project目录

MyClassPathXMLApplicationContext读取xml,以及实例化bean。

因为是一开始实例化配置文件所有bean,所以需要构造器完成这些工作。

package test;

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;

public class MyClassPathXMLApplicationContext {
    private List<BeanDefinition> beanDefines = new ArrayList<BeanDefinition>();
    private Map<String, Object> sigletons = new HashMap<String, Object>();
    
    public MyClassPathXMLApplicationContext(String filename){
        this.readXML(filename);
        this.instanceBeans();
    }
    /**
     * 完成bean的实例化
     */
    private void instanceBeans() {
        for(BeanDefinition beanDefinition : beanDefines){
            try {
                if(beanDefinition.getClassName()!=null && !"".equals(beanDefinition.getClassName().trim()))
                    sigletons.put(beanDefinition.getId(), Class.forName(beanDefinition.getClassName()).newInstance());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
    }
    /**
     * 读取xml配置文件
     * @param filename
     */
    private void readXML(String filename) {
            SAXReader saxReader = new SAXReader();   
            Document document=null;   
            try{
             URL xmlpath = this.getClass().getClassLoader().getResource(filename);
             document = saxReader.read(xmlpath);
             Map<String,String> nsMap = new HashMap<String,String>();
             nsMap.put("ns","http://www.springframework.org/schema/beans");//加入命名空间
             XPath xsub = document.createXPath("//ns:beans/ns:bean");//创建beans/bean查询路径
             xsub.setNamespaceURIs(nsMap);//设置命名空间
             List<Element> beans = xsub.selectNodes(document);//获取文档下所有bean节点 
             for(Element element: beans){
                String id = element.attributeValue("id");//获取id属性值
                String clazz = element.attributeValue("class"); //获取class属性值        
                BeanDefinition beanDefine = new BeanDefinition(id, clazz);
                beanDefines.add(beanDefine);
             }   
            }catch(Exception e){   
                e.printStackTrace();
            }
    }
    /**
     * 获取bean实例
     * @param beanName
     * @return
     */
    public Object getBean(String beanName){
        return this.sigletons.get(beanName);
    }
}

bean的定义类:

package test;

public class BeanDefinition {
    private String id;
    private String className;
    
    public BeanDefinition(String id, String className) {
        this.id = id;
        this.className = className;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getClassName() {
        return className;
    }
    public void setClassName(String className) {
        this.className = className;
    }
    
}

测试类:

package test;

import org.junit.BeforeClass;
import org.junit.Test;

import service.MyAction;

public class SpringTest {

    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
    }

    @Test public void instanceSpring(){
        MyClassPathXMLApplicationContext ctx = 
                new MyClassPathXMLApplicationContext("applicationContext.xml");
        MyAction ma = (MyAction)ctx.getBean("myaction");
        ma.sayHello();
    }
}

 applicationContext.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-3.1.xsd">
    
        <bean id = "myaction" class = "service.MyAction"></bean>
   
</beans>
原文地址:https://www.cnblogs.com/rixiang/p/5185848.html