類比Spring中applicationContext.xml設定檔初始化bean的過程

來源:互聯網
上載者:User

標籤:

package com.xiaohao.action;import java.io.File;import java.lang.reflect.Method;import java.util.Collections;import java.util.HashMap;import java.util.Map;import org.dom4j.Document;import org.dom4j.Element;import org.dom4j.io.SAXReader;/** * 需要匯入dom4j的jar包  * @author 小浩 * @建立日期 2015-4-4 */public class BeanFactory {/**     * 儲存容器中所有單例模式的bean執行個體,這裡的hashMap是安全執行緒的     *     */private static Map<String,Object> beanPool=Collections.synchronizedMap(new HashMap<String,Object>());    //儲存檔案對應的Document對象    private Document document;    //儲存設定檔裡的根項目    private Element root;        /**     * 構造方法,指定需要讀取的檔案的路徑     * @param filePath     * @throws Exception     */    public BeanFactory(String filePath) throws Exception{          //使用dom4j讀取xml設定檔    SAXReader reader=new SAXReader();        document=reader.read(new File(filePath));    root=document.getRootElement();     //進行容器的初始化        initPool();        //初始化單例bean的屬性        initProp();      }        /**     * 擷取指定的bean     * @param name     * @return     * @throws Exception     */public static Object getBean(String name) throws Exception {    Object target = beanPool.get(name);        //對於單例bean,容器已經初始化了所有的Bean執行個體        if(target.getClass() != String.class){            return target;        }else{            String clazz = (String)target;            //對於非單例的並未注入屬性值            return Class.forName(clazz).newInstance();        }}            /**     * 初始化容器中的所有單例bean     * */    private void initPool() throws Exception{        //遍曆設定檔中的每個<bean ../>元素        for(Object obj:root.elements()){            Element beanElement = (Element)obj;            //擷取Bean元素中的id屬性            String beanId = beanElement.attributeValue("id");            //擷取bean元素中的class屬性            String beanClazz = beanElement.attributeValue("class");             //擷取bean元素中的scope屬性            String beanScope = beanElement.attributeValue("scope");             //如果scope屬性不存在或為singleton            if(beanScope == null|| beanScope.equals("singleton")){                //以預設構造方法建立bean執行個體,並將其放入beanPool中                beanPool.put(beanId, Class.forName(beanClazz).newInstance());   //利用反射的技術            }else{                //對於非單例的,存放Bean實作類別的類名               beanPool.put(beanId, beanClazz);            }        }            }/** * 初始化容器中的單例bean * */private void initProp() throws Exception{    //遍曆設定檔中的所有bean元素,即根節點的子節點    for(Object object:root.elements()){        Element beanElement = (Element)object;        //擷取Bean元素中的id屬性        String beanId = beanElement.attributeValue("id");        //擷取bean元素中的scope屬性        String beanScope = beanElement.attributeValue("scope");         //如果scope屬性不存在或為singleton        if(beanScope == null|| beanScope.equals("singleton")){            //取出beanPool的指定bean執行個體            Object bean = beanPool.get(beanId);            //遍曆bean屬性下的所有property屬性            for(Object prop: beanElement.elements()){                Element probElement = (Element)prop;                //擷取property的name屬性                String propName = probElement.attributeValue("name");                //擷取property的value屬性                String propValue = probElement.attributeValue("value");                //擷取property的ref屬性                String propRef = probElement.attributeValue("ref");                //將屬性名稱的首字母大寫                String propNameCamelize = propName.substring(0,1).toUpperCase()                    +propName.substring(1, propName.length());                //如果value值存在                if(propValue != null&&propValue.length()> 0){                    //擷取設定注入所需要的setter方法                    java.lang.reflect.Method setter = bean.getClass().getMethod("set"+propNameCamelize, String.class);                    //執行setter注入                    setter.invoke(bean, propValue);                }                if(propRef != null&&propRef.length()> 0){                    //取得需要被注入的bean執行個體                    Object target = beanPool.get(propRef);                    //如果不存在                    if(target == null){                        //此處處理單例bean依賴於非單例bean的情形                    }                    //定義設值注入需要的setter方法                    Method setter = null;                    //遍曆target對象所實現的所有方法                    for(Class superInterface: target.getClass().getInterfaces()){                        try{                            //擷取設定注入所需要的setter方法                            setter = bean.getClass().getMethod("set"+propNameCamelize, superInterface);                            //如果成功擷取,跳出迴圈                            break;                        }catch (Exception e) {                            //如果沒有找到就繼續下次迴圈                            continue;                        }                    }                    //如果setter方法依然是null,直接取得target的實作類別對應的setter方法                    if(setter == null){                        setter = bean.getClass().getMethod("set"+propNameCamelize, target.getClass());                    }                    //執行setter注入                    setter.invoke(bean, target);                }                            }    }    }}}

  

類比Spring中applicationContext.xml設定檔初始化bean的過程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.