简单实现以下Spring的IOC

SpringIOC的简单实现

1. spring IOC简介

ioc: 全文是Inversion of Control。翻译过来就是控制反转,意思是对象之间的关系不再由传统的程序来控制,而是由spring容器来统一控制这些对象创建、协调、销毁,而对象只需要完成业务逻辑即可。

2. IOC的简单实现

  1. 加载 xml 配置文件,遍历其中的标签
  2. 获取标签中的 id 和 class 属性,加载 class 属性对应的类,并创建 bean
  3. 遍历标签中的标签,获取属性值,并将属性值填充到 bean 中
  4. 将 bean 注册到 bean 容器中

测试使用的实体类一 :Car

/**
 * @author crazyang
 * @date 2019/8/21
 * @Description:
 */
public class Car {
    private String name;
    private String length;
    private String width;
    private String height;
    private Wheel wheel;
    //省略getter/setter
}

测试使用的实体类二:Wheel

/**
 * @author crazyang
 * @date 2019/8/21
 * @Description:
 */
public class Wheel {
    private String brand;
    private String specification;
     //省略getter/setter
}

springIoc的简单实现类

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * @author crazyang
 * @date 2019/8/21
 * @Description:
 */
public class SimpleIOC {

    private Map<String, Object> beanMap = new HashMap<>();

    public SimpleIOC(String location) throws Exception {
        loadBeans(location);
    }

    public Object getBean(String name) {
        Object bean = beanMap.get(name);
        if (bean == null) {
            throw new IllegalArgumentException("there is no bean with name" + name);
        }
        return bean;
    }

    private void loadBeans(String location) throws Exception {
        //加载xml配置文件
        InputStream inputStream = new FileInputStream(location);
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = factory.newDocumentBuilder();
        Document doc = docBuilder.parse(inputStream);
        Element root = doc.getDocumentElement();
        NodeList nodes = root.getChildNodes();

        //遍历<bean>标签
        for (int i = 0; i < nodes.getLength(); i++) {
            Node node = nodes.item(i);
            if (node instanceof Element) {
                Element element = (Element) node;
                String id = element.getAttribute("id");
                String className = element.getAttribute("class");
                //加载beanClass
                Class beanClass = null;
                try {
                    beanClass = Class.forName(className);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                    return;
                }
                //创建bean
                Object bean = beanClass.newInstance();
                //遍历<property>标签
                NodeList propertyNodes = element.getElementsByTagName("property");
                for (int j = 0; j < propertyNodes.getLength(); j++) {
                    Node propertyNode = propertyNodes.item(j);
                    if (propertyNode instanceof Element) {
                        Element propertyElement = (Element) propertyNode;
                        String name = propertyElement.getAttribute("name");
                        String value = propertyElement.getAttribute("value");
                        //利用反射将bean相关字段访问权限设为可访问
                        Field declareField = bean.getClass().getDeclaredField(name);
                        declareField.setAccessible(true);
                        if (value != null && value.length() > 0) {
                            declareField.set(bean, value);
                        } else {
                            String ref = propertyElement.getAttribute("ref");
                            if (ref == null && ref.length() == 0) {
                                throw new IllegalArgumentException("ref config error");
                            }
                            //将引用填充到相关字段中
                            declareField.set(bean, getBean(ref));
                        }
                        //将bean注册到bean容器中
                        registerBean(id, bean);
                    }
                }

            }
        }

    }

    private void registerBean(String id, Object bean) {
        beanMap.put(id, bean);
    }
}

springIOC的配置文件,路径是放在resource下面

<beans>
    <bean id="wheel" class="com.yangzhou.utils.Spring.ioc.Wheel">
        <property name="brand" value="Michelin"/>
        <property name="specification" value="265/60 R18"/>
    </bean>

    <bean id="car" class="com.yangzhou.utils.Spring.ioc.Car">
        <property name="name" value="Mercedes Benz G 500"/>
        <property name="length" value="4717mm"/>
        <property name="width" value="1855mm"/>
        <property name="height" value="1949mm"/>
        <property name="wheel" ref="wheel"/>
    </bean>
</beans>

springIoc的测试类

/**
 * @author zhouyang
 * @date 2019/8/21
 * @Description:
 */
public class SpringIOCTest {

    public static void main(String[] args)throws Exception {
        String path = "D:\\project\\test\\utils\\src\\main\\resources\\spring-test.xml";
        String location = SpringIOCTest.class.getClassLoader().getResource("spring-test.xml").getFile();
        SimpleIOC bf = new SimpleIOC(location);
        Wheel wheel = (Wheel) bf.getBean("wheel");
        System.out.println(wheel);
        Car car = (Car) bf.getBean("car");
        System.out.println(car);
        System.out.println(car.getName());
    }
}

输出结果:

com.yangzhou.utils.Spring.ioc.Wheel@5a07e868
com.yangzhou.utils.Spring.ioc.Car@76ed5528
Mercedes Benz G 500
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章