模拟Spring容器管理bean

package com.spring;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;

import com.vo.BeanDefinition;

/**
 * 简单模拟spring的ClassPathXmlApplicationContext spring容器管理bean
 *
 */
@SuppressWarnings("unchecked")
public class MyApplicationContext
{
    private List<BeanDefinition> list = new ArrayList<BeanDefinition>();
    private Map<String, Object> sigletons = new HashMap<String, Object>();

    public MyApplicationContext(String fileName)
    {
        this.readXML(fileName);
        try
        {
            instanceBeans();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    /**
     * 实例化所有bean
     *
     * @throws InstantiationException
     * @throws IllegalAccessException
     * @throws ClassNotFoundException
     */
    private void instanceBeans() throws InstantiationException,
            IllegalAccessException, ClassNotFoundException
    {
        for (BeanDefinition bean : list)
        {
            if (null != bean.getClassName() && bean.getClassName().length() > 0)
                sigletons.put(bean.getId(), Class.forName(bean.getClassName())
                        .newInstance());
        }
    }

    /**
     * 读取xml配置
     *
     * @param fileName
     */
    public void readXML(String fileName)
    {
        SAXBuilder builder = new SAXBuilder();
        URL url = this.getClass().getClassLoader().getResource(fileName);
        try
        {
            Document doc = builder.build(url);
            XPath xpath = XPath.newInstance("//ns:beans/ns:bean");
            xpath.addNamespace("ns",
                    "http://www.springframework.org/schema/beans");
            List<Element> beans = xpath.selectNodes(doc);
            for (Element bean : beans)
            {
                String id = bean.getAttributeValue("id");
                String className = bean.getAttributeValue("class");
                BeanDefinition beanDefinition = new BeanDefinition(id,
                        className);
                list.add(beanDefinition);
            }

        }
        catch (JDOMException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    /**
     * 得到指定id的bean
     *
     * @param id
     * @return
     */
    public Object getBean(String id)
    {
        return sigletons.get(id);
    }
}
    测试:

@Test
    public void testMyUserService()
    {
        MyApplicationContext ctx = new MyApplicationContext("beans.xml");
        UserService us = (UserService) ctx.getBean("userService");
        us.print();
    }

猜你喜欢

转载自88548886.iteye.com/blog/1561637
今日推荐