SpringIOC框架详解

1、SpringIOC是什么?

  就是一个用来管理实体类bean的容器

2、创建cppdy.xml文件(模拟springmvc.xml文件)

<?xml version="1.0" encoding="UTF-8"?>
<beans>
    <bean id="user1" class="com.cppdy.UserTest">
        <property key="name" value="cppdy" />
        <property key="sex" value="boy" />
    </bean>
    <bean id="user2" class="com.cppdy.UserTest">
        <property key="name" value="吹泡泡的魚" />
        <property key="sex" value="男" />
    </bean>
</beans>

3、创建SpringIOCDemo类(模拟SpringIOC获取bean)

package com.cppdy;

import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

class ApplicationResouceReader{
    private String url;
    
    public ApplicationResouceReader(String url) {
        this.url=url;
    }
    
    public Object getBean(String id) throws Exception {
        //获取到xml文件
        InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream(url);
        SAXReader saxReader = new SAXReader();
        Document read = saxReader.read(resourceAsStream);
        //解析xml,获取到beanId相同的节点
        Element beans = read.getRootElement();
        List<Element> beanList = beans.elements();
        Element ele;
        for (int i = 0; i < beanList.size(); i++) {
            ele=beanList.get(i);
            if(!ele.attributeValue("id").equals(id)) {
                continue;
            }
            //拿到class全路径,方便之后反射
            String beanClass=ele.attributeValue("class");
            //反射出实体类
            Class<?> forName = Class.forName(beanClass);
            Object userInstance = forName.newInstance();
            
            //获取当前符合id节点的属性列表
            List<Element> attrsList = ele.elements();
            //对属性进行赋值
            for (int j = 0; j < attrsList.size(); j++) {
                String key_zhi = attrsList.get(j).attributeValue("key");
                Field declaredField = forName.getDeclaredField(key_zhi);
                String value_zhi = attrsList.get(j).attributeValue("value");
                declaredField.setAccessible(true);
                declaredField.set(userInstance, value_zhi);
            }
            return userInstance;
        }
        return null;
    }
}

public class SpringIOCDemo {

    public static void main(String[] args) throws Exception {
        ApplicationResouceReader arr=new ApplicationResouceReader("cppdy.xml");
        UserTest bean = (UserTest) arr.getBean("user1");
        System.out.println(bean.toString());
    }

}

 

posted @ 2018-11-27 23:03  知识追求者  阅读(279)  评论(0编辑  收藏  举报