编码剖析Spring装配基本属性的原理---自定义的Spring容器

来源:互联网 发布:js判断变量是否是数组 编辑:程序博客网 时间:2024/05/16 08:45

PolarWolfApplicationContext.java--------自定义的极地狼容器
package junit.test;

import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.XPath;
import org.dom4j.io.SAXReader;

/**
 * @ClassName: PolarWolfApplicationContext
 * @Description: TODO(极地狼容器)
 * @author Mr.yang
 * @date 2010-8-17 上午11:17:36
 *
 */
public class PolarWolfClassPathXMLApplicationContext {
        private List<BeanDefinition> beanDefines = new ArrayList<BeanDefinition>();
        private Map<String, Object> sigletons = new HashMap<String, Object>();

        public PolarWolfClassPathXMLApplicationContext(String... fileNames) {
                this.readXML(fileNames);
                this.instanceBeans();
                this.injectObject();
        }

        /**
         * @Title: injectObject
         * @Description: TODO(依赖注入)
         * @param 设定文件
         * @return void 返回类型
         * @throws
         */
        private void injectObject() {
                for (BeanDefinition beanDefinition : beanDefines) {
                        Object bean = sigletons.get(beanDefinition.getId());
                        if (bean != null) {
                                try {
                                        PropertyDescriptor[] propertyDescriptors = Introspector
                                                        .getBeanInfo(bean.getClass())
                                                        .getPropertyDescriptors();//得到bean对象的所有属性描述
                                        for(PropertyDefinition property : beanDefinition.getPropertys()){
                                                for(PropertyDescriptor propertyDescriptor : propertyDescriptors){
                                                        if(property.getName().equals(propertyDescriptor.getName())){//找到配置文件中bean的属性与bean对象属性描述中一致的属性
                                                                Method setter = propertyDescriptor.getWriteMethod();//获取属性的setter方法
                                                                if(setter!=null){
                                                                        Object value = null;
                                                                        if(property.getRef()!=null && !"".equals(property.getRef().trim())){
                                                                                value = sigletons.get(property.getRef());//获取要注入的实例
                                                                        }else{
                                                                                value = ConvertUtils.convert(property.getValue(), propertyDescriptor.getPropertyType());//利用beanUtils包转换数据类型
                                                                        }
                                                                        setter.setAccessible(true);//设置私有setter方法也可以调用
                                                                        setter.invoke(bean,value );//把引用对象注入到属性
                                                                       
                                                                }
                                                                break;
                                                        }
                                                }
                                        }
                                } catch (Exception e) {
                                        // TODO: handle exception
                                }
                        }
                }
        }

        /**
         * @Title: instanceBeans
         * @Description: TODO(实例化Beans)
         * @param 设定文件
         * @return void 返回类型
         * @throws
         */
        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());//调用bean对应的默认构造函数实例化bean,并装载到容器集合中
                        } catch (Exception e) {
                                e.printStackTrace();
                        }
                }
        }

        /**
         * @Title: readXML
         * @Description: TODO(使用dom4j读取xml配置文件)
         * @param @param fileNames 设定文件
         * @return void 返回类型
         * @throws
         */
        private void readXML(String[] fileNames) {
                SAXReader saxReader = new SAXReader();//创建读取器
                Document document = null;//定义文档
                for (String fileName : fileNames) {//迭代所有需要加载的bean配置文件
                        try {
                                URL xmlPath = this.getClass().getClassLoader().getResource(
                                                fileName);//创建配置文件URL
                                document = saxReader.read(xmlPath);//获取文档内容
                                Map<String, String> nsMap = new HashMap<String, String>();//定义命名空间HashMap
                                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 bean : beans) {
                                        String id = bean.attributeValue("id");// 获取id属性值
                                        String className = bean.attributeValue("class");// 获取class属性值
                                        BeanDefinition beanDefine = new BeanDefinition(id,
                                                        className);
                                        XPath propertySub = bean.createXPath("ns:property");// 创建bean内部查询路径
                                        propertySub.setNamespaceURIs(nsMap);// 设置命名空间
                                        List<Element> propertys = propertySub.selectNodes(bean);
                                        for (Element property : propertys) {
                                                String name = property.attributeValue("name");//得到属性值
                                                String ref = property.attributeValue("ref");
                                                String value = property.attributeValue("value");
                                                PropertyDefinition proper = new PropertyDefinition(
                                                                name, ref,value);
                                                beanDefine.getPropertys().add(proper);
                                        }
                                        beanDefines.add(beanDefine);
                                }
                        } catch (Exception e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                        }

                }
        }

        /**
         * @Title: getBean
         * @Description: TODO(获取bean实例)
         * @param @param beanName
         * @param @return 设定文件
         * @return Object 返回类型
         * @throws
         */
        public Object getBean(String beanName) {
                return this.sigletons.get(beanName);
        }
}