码迷,mamicode.com
首页 > 其他好文 > 详细

一个简单IOC与DI示例

时间:2018-02-18 21:03:02      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:eth   class   nfa   xml配置   port   实例化   parse   double   一个   

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);
        }
    }
}

 

一个简单IOC与DI示例

标签:eth   class   nfa   xml配置   port   实例化   parse   double   一个   

原文地址:https://www.cnblogs.com/gdwkong/p/8453159.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!