Spring记录之模拟IoC(三)

7 篇文章 0 订阅
6 篇文章 0 订阅

模拟Spring IoC容器 3.0

从xml文件中读取的value值,是String类型,与Java Bean定义的属性,如int,double类型之间如何实现转换呢?

上次说过,Apache Commons BeanUtils包,http://commons.apache.org/proper/commons-beanutils/ 该包集成了许多转化器Converter

用它来实现。

步骤一:加jar包
commons-logging-1.2.jar
commons-beanutils-1.8.3.jar
步骤二:修改容器实现类

修改值注入的地方

package spring.container;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.beanutils.BeanUtils;

import spring.config.Bean;
import spring.config.Property;
import spring.parser.ConfigParser;

/**
 * @author Administrator
 * 
 */
public class Dom4jClassPathXmlApplicationContext implements BeanFactory {

    //beans from xml config file
    private Map<String, Bean> beans;

    // container to store bean
    private Map<String, Object> contextMap = new HashMap<String, Object>();

    // parse xml file instantly this class is initializing
    public Dom4jClassPathXmlApplicationContext(String path) {
        beans = ConfigParser.dom4jParser(path);

        if (beans != null) {
            // loop beans
            for (Entry<String, Bean> en : beans.entrySet()) {

                String id = en.getKey();
                Bean bean = en.getValue();

                Object existBean = contextMap.get("id");

                // bean is not initialized and scope is singleton
                if (existBean == null && bean.getScope().equals("singleton")) {

                    // initialize bean. 需检验是否已经注入
                    // Bean must be checked if it is already been initialized
                    // before this process
                    Object obj = createBean(bean);

                    // put beans into the container
                    contextMap.put(id, obj);
                }

            }
        }
    }

    /**
     * @param bean
     * @return
     */
    private Object createBean(Bean bean) {

        String className = null;

        // user reflection
        Class clazz = null;
        try {
            className = bean.getClassName();
            clazz = Class.forName(className);
        } catch (ClassNotFoundException | NullPointerException e) {
            e.printStackTrace();
            throw new RuntimeException(className
                    + " not found in xml config file.");
        }

        // generate Objection
        Object object = null;
        try {
            object = clazz.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
            throw new RuntimeException(
                    "no  default constructor defined in " + className);
        }


        /**
         * <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
         *      <property name="driverClassName" value="${jdbc.driverClass}"/>
         *      <property name="url" value="${jdbc.url}"/>
         * </bean>  
         */

        // inject property
        if (bean.getProperties() != null) {


            for (Property properties : bean.getProperties()) {

                String propName = null;
                Method setterMethod = null;
                try {

                    propName = properties.getName();

                    // using setter to inject value <property name="name"
                    // value="changing"/>, <property name="name" ref="ref"/>
                    setterMethod = BeanMethod.getWriterMethod(object,propName);

                } catch (NullPointerException e) {
                    e.printStackTrace();
                    throw new RuntimeException("property name is not defined.");
                }


                // inject value into object using setter
                // 这里是值注入,此处通过BeanUtils.populate()方法注入,该方法实现了自动类型转换
                if (properties.getValue() != null) {


                    //use apache BeanUtils tool to inject value so that automation of type change can be done
                    Map<String, String[]> paraMap = new HashMap<String, String[]>();
                    paraMap.put(propName, new String[]{properties.getValue()});

                    try {
                        BeanUtils.populate(object, paraMap);
                    } catch (IllegalAccessException | InvocationTargetException e) {
                        e.printStackTrace();
                    }

                }

                // inject another Object
                if (properties.getRef() != null) {
                    // get ref instance
                    Object refBean = contextMap.get(properties.getRef());

                    // refBean is not generated. Generate it by recursion
                    if (refBean == null) {

                        refBean = createBean(beans.get(properties.getRef()));

                        if(beans.get(properties.getRef()).getScope().equals("singleton")){
                            // put refBean into Container if scope in the xml file is singleton
                            contextMap.put(properties.getRef(), refBean);
                        }
                    }

                    //setter to inject value or ref
                    try {

                        setterMethod.invoke(object, refBean);

                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (IllegalArgumentException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }
                }


            }
        }

        return object;
    }

    @Override
    public Object getBean(String id) {
        Object bean = contextMap.get(id);

        //if scope is not singleton, then bean does not exist in contextMap and should be null
        if(bean == null){
            bean = createBean(beans.get(id));
        }
        return bean;
    }

}
步骤三:测试
//在Animal类中增加int类型的age属性,设置getter/setter
<bean id="animal" class="spring.beans.Animal">
    <property name="age" value="150"/>
</bean>
@Test
    public void testBean(){
        Dom4jClassPathXmlApplicationContext context = new Dom4jClassPathXmlApplicationContext("/bean.xml");
        Animal animal = (Animal)context.getBean("animal");
        System.out.println(animal.getAge());
    }       
结果

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值