您的位置:首页 > 编程语言 > Java开发

自定义java类实现类似spring的依赖注入功能

2012-08-21 23:26 501 查看
package com.zhjjie.util;

import java.io.File;

import java.io.IOException;

import java.lang.reflect.Method;

import java.util.Collections;

import java.util.HashMap;

import java.util.Locale;

import java.util.Map;

import org.dom4j.Document;

import org.dom4j.Element;

import org.dom4j.io.SAXReader;

import org.springframework.beans.BeansException;

import org.springframework.beans.factory.BeanFactory;

import org.springframework.beans.factory.NoSuchBeanDefinitionException;

import org.springframework.beans.factory.config.AutowireCapableBeanFactory;

import org.springframework.context.ApplicationContext;

import org.springframework.context.ApplicationEvent;

import org.springframework.context.MessageSourceResolvable;

import org.springframework.context.NoSuchMessageException;

import org.springframework.core.io.Resource;

import com.zhjjie.action.StudentAction;

/**

 * @author ; Administrator

 * @Description : TODO

 * @CreateDate ; Aug 21, 2012 8:56:56 PM

 * @lastModified ; Aug 21, 2012 8:56:56 PM

 * @version ; 1.0

 */

public class MyXmlApplicationContextUtil implements ApplicationContext {

    //保存容器中所有单例模式的bean

    private Map<String,Object> objPool = Collections.synchronizedMap(new HashMap<String,Object>());

    //保存配置文件中对应的文档对象

    private Document doc;

    //保存配置文件里面的根元素

    private Element root;

    

    /**

     *

     */

    public MyXmlApplicationContextUtil() {

        super();

        

    }

    /**

     *

     */

    public MyXmlApplicationContextUtil(String filePath)throws Exception{

        SAXReader reader = new SAXReader();

        doc = reader.read(new File(filePath));

        root = doc.getRootElement();

        initPool();

        initProp();

    }

    

    

    public Object getBean(String name) throws BeansException {

        Object target = objPool.get(name);

        Object obj = null;

        if(target.getClass() != String.class){

            obj =  target;

        }else{

            String clazz = (String)target;

            try{

                obj = Class.forName(clazz).newInstance();

            }catch(Exception e){

                e.printStackTrace();

            }

            

        }

        return obj;

    }

    

    private void initPool()throws Exception{

        for(Object obj:root.elements()){//遍历每个bean元素

            Element ele = (Element)obj;

            String beanId = ele.attributeValue("id");

            String beanClazz = ele.attributeValue("class");

            String beanScope = ele.attributeValue("scope");

            

            if(beanScope == null || beanScope.equals("singleton")){

                objPool.put(beanId, Class.forName(beanClazz).newInstance());

            }else{

                objPool.put(beanId, beanClazz);

            }

        }

    }

    

    private void initProp()throws Exception{

        for(Object obj:root.elements()){//遍历每个bean元素

            Element ele = (Element)obj;

            String beanId = ele.attributeValue("id");

            String beanScope = ele.attributeValue("scope");

            

            if(beanScope == null || beanScope.equals("beanScope")){

                Object bean = objPool.get(beanId);

                for(Object prop:ele.elements()){

                    Element propElem = (Element)prop;

                    String propName = propElem.attributeValue("name");

                    String propVal = propElem.attributeValue("value");

                    String propRef = propElem.attributeValue("ref");

                    

                    String propNameOfFirstLetter = propName.substring(0,1).toUpperCase()+propName.substring(1);

                    

                    if(propVal != null && propVal.length()>0){

                        Method setter = bean.getClass().getMethod("set" + propNameOfFirstLetter, String.class);

                        setter.invoke(bean, propVal);

                    }

                    

                    if(propRef !=null && propRef.length()>0){

                        Object target = objPool.get(propRef);

                        if(target == null){};

                        Method setter = null;

                        for(Class superInterface:target.getClass().getInterfaces()){

                            try{

                                setter = bean.getClass().getMethod("set" + propNameOfFirstLetter, superInterface);

                                setter.invoke(bean, propVal);

                                break;

                            }catch(NoSuchMethodException e){

                                continue;

                            }

                        }

                        if(setter == null){

                            setter = bean.getClass().getMethod("set" + propNameOfFirstLetter, target.getClass());

                        }

                        setter.invoke(bean, propVal);

                        

                    }

                }

                

            }else{

                //objPool.put(beanId, beanClazz);

            }

        }

    }

    public static void main(String[] args)throws Exception{

    

        

        ApplicationContext ac = new MyXmlApplicationContextUtil("D:\\Myeclipse6.5\\webBookShop\\WebRoot\\bean.xml");

        

        StudentAction s = (StudentAction)ac.getBean("StudentAction");

        System.out.println(s);

    }

    

   

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息