一個簡單IOC與DI樣本,簡單IOCDI樣本

來源:互聯網
上載者:User

一個簡單IOC與DI樣本,簡單IOCDI樣本

1、通過bean工廠實現讀取xml檔案,並執行個體化對象,實現自動注入。
package com.pri.test;import com.pri.factory.BeanFactory;import com.pri.service.UserService;import org.junit.Test;public class BeanFactoryTest {    @Test    public void test(){        BeanFactory beanFactory = BeanFactory.getBeanFactory();        UserService user = (UserService)beanFactory.getBean("user");        user.save();    }}

2、xml設定檔:

<?xml version="1.0" encoding="UTF-8"?><beans >    <bean id="user" class="com.pri.service.impl.UserServiceImpl01">        <property name="name" value="李四"/>    </bean></beans>

3、執行個體對象:

package com.pri.service.impl;import com.pri.service.UserService;public class UserServiceImpl01 implements UserService{    private String name;    public String getName() { return name;}    public void setName(String name) { this.name = name;}    @Override    public void save(){        System.out.println("UserService被調用........::"+name);    }}

4、BeanFactory工廠:

package com.pri.factory;import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.Element;import org.dom4j.io.SAXReader;import java.beans.IntrospectionException;import java.beans.PropertyDescriptor;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;public class BeanFactory {    /**     * 私人化構造,禁止以new的方式擷取BeanFactory執行個體     */    private BeanFactory(){}    /**     * 靜態內部類,保證只有一個BeanFactory     */    static class SingleBeanFactory{        static BeanFactory BEANFACTORY = new BeanFactory();    }    /**     * 對外提供一個擷取BeanFactory方法     * @return     */    public static BeanFactory getBeanFactory(){        return SingleBeanFactory.BEANFACTORY;    }    public Object getBean(String id) {        try {            Element element = getElement(id);            String classPath = element.attribute("class").getValue();            //根據類的全限定名建立Class對象            Class<?> clazz = Class.forName(classPath);            //建立執行個體            Object obj = clazz.newInstance();            //為bean對象賦值            setAttributeValue(clazz,element,obj);            return obj;        } catch (Exception e) {            e.printStackTrace();            return null;        }    }    private  Element getElement(String id) throws DocumentException {        SAXReader saxReader = new SAXReader();        Document document = saxReader.read("src/myconfig.xml");        //精確定位到id屬性值為傳入字串的bean元素        return (Element) document.selectSingleNode("//bean[@id='" + id + "']");    }    private void setAttributeValue(Class<?> clazz, Element element,Object obj) throws IntrospectionException, IllegalAccessException, InvocationTargetException {        Element subElement = element.element("property");        //使用set方法賦值        if (subElement != null) {            String name = subElement.attributeValue("name");            String valueStr = subElement.attributeValue("value");            //建立屬性描述器            PropertyDescriptor descriptor = new PropertyDescriptor(name, clazz);            //擷取該屬性的修飾符            String s = descriptor.getPropertyType().getName();            //獲得寫方法            Method writeMethod = descriptor.getWriteMethod();            //調用寫方法            Object value = null;            if (s.equalsIgnoreCase("int")){                value = Integer.parseInt(valueStr);            }else if (s.equalsIgnoreCase("long")){                value = Long.parseLong(valueStr);            }else if (s.equalsIgnoreCase("short")){                value = Short.parseShort(valueStr);            }else if (s.equalsIgnoreCase("double")){                value = Double.parseDouble(valueStr);            }else if (s.equalsIgnoreCase("float")){               value = Float.parseFloat(valueStr);            }else if (s.equalsIgnoreCase("byte")) {                value = Byte.valueOf(valueStr);            }else{                value = valueStr;            }            writeMethod.invoke(obj, value);        }    }}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.