简单实现Spring IOC (单例模式)(解析XML方式)

基于XML方式的依赖注入,主要是基于XML的解析类的反射机制 

主要思路:

           1、解析xml文件

           2、获取xml文件所有的节点内容

           3、根据类路径反射类

           4、注入属性信息

项目基本框架:

简单实现Spring IOC (单例模式)(解析XML方式)_第1张图片

1、首先创建普通maven项目,导入dom4j、Spring context等的依赖

pom.xml(我直接复制的,所以spring的基本依赖基本都有,可以自己选择性导入)




  4.0.0

  com.spring.xml
  ioc
  1.0-SNAPSHOT

  ioc
  
  http://www.example.com

  
    UTF-8
    1.7
    1.7
    
    4.3.7.RELEASE
  

  

    
      junit
      junit
      4.11
      test
    

    
      dom4j
      dom4j
      1.6.1
    

    
    
      org.springframework
      spring-aop
      ${org.springframework.version}
    
    
      org.springframework
      spring-aspects
      ${org.springframework.version}
    
    
      org.springframework
      spring-beans
      ${org.springframework.version}
    
    
      org.springframework
      spring-context
      ${org.springframework.version}
    
    
      org.springframework
      spring-context-support
      ${org.springframework.version}
    
    
      org.springframework
      spring-core
      ${org.springframework.version}
    
    
      org.springframework
      spring-expression
      ${org.springframework.version}
    
    
      org.springframework
      spring-instrument
      ${org.springframework.version}
    
    
      org.springframework
      spring-instrument-tomcat
      ${org.springframework.version}
    
    
      org.springframework
      spring-jdbc
      ${org.springframework.version}
    
    
      org.springframework
      spring-jms
      ${org.springframework.version}
    
    
      org.springframework
      spring-messaging
      ${org.springframework.version}
    
    
      org.springframework
      spring-orm
      ${org.springframework.version}
    
    
      org.springframework
      spring-oxm
      ${org.springframework.version}
    
    
      org.springframework
      spring-test
      ${org.springframework.version}
    
    
      org.springframework
      spring-tx
      ${org.springframework.version}
    
    
      org.springframework
      spring-web
      ${org.springframework.version}
    
    
      org.springframework
      spring-webmvc
      ${org.springframework.version}
    
    
      org.springframework
      spring-webmvc-portlet
      ${org.springframework.version}
    
    
      org.springframework
      spring-websocket
      ${org.springframework.version}
    
    
  

  
    
      
        
          maven-clean-plugin
          3.0.0
        
        
        
          maven-resources-plugin
          3.0.2
        
        
          maven-compiler-plugin
          3.7.0
        
        
          maven-surefire-plugin
          2.20.1
        
        
          maven-jar-plugin
          3.0.2
        
        
          maven-install-plugin
          2.5.2
        
        
          maven-deploy-plugin
          2.8.2
        
      
    
  

2、创建bean

package com.spring.xml.bean;

public class Car {
    private String name;
    private int price;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Car{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
    }
}

 3、创建applicationContext.xml




    
        
        
    

    
        
        
    

4、创建类XmlApplicationContext

package com.spring.xml.utils;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;

/**
 * 1、解析xml文件
 * 2、获取xml文件所有的节点内容
 * 3、根据类路径反射类
 * 4、注入属性信息
 */
public class XmlApplicationContext {
    // xml路径
    private String xmlPath;
    // 存放bean
    private Map map = null;
    // 存放从xml解析出来的类的需要注入的属性名和属性值
    private List propertyName = new ArrayList<>();
    private List propertyData = new ArrayList<>();

    public XmlApplicationContext(String xmlPath) {
        this.xmlPath = xmlPath;
        try {
            getAllElements();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 1、读取xml文件,返回根节点
    public Iterator readXML() throws DocumentException, FileNotFoundException {
        SAXReader reader = new SAXReader();
        File file = ResourceUtils.getFile("classpath:" + xmlPath);
        Document document = reader.read(file);
        Element rootElement = document.getRootElement();
        Iterator iterator = rootElement.elementIterator();
        return iterator;
    }

    // 2、获取xml文件所有的节点内容
    public void getAllElements() throws Exception {
        Iterator iterator = readXML();
        List classList = new ArrayList<>();
        List idList = new ArrayList<>();
        Class clazz = null;

        while (iterator.hasNext()) {
            Element bean = (Element) iterator.next();
            //System.out.println(next.getName())
            // 获取bean的id,class
            Iterator beanAttributes = bean.attributeIterator();
            String id = null;
            while (beanAttributes.hasNext()) {
                Attribute attribute = (Attribute) beanAttributes.next();
                String classPropertyName = attribute.getName();
                String className = (String) attribute.getData();
                if (classPropertyName.equals("class")) {
                    clazz = Class.forName(className);
                } else
                    id = className;

            }
            // System.out.println(id);
            idList.add(id);
            // 获取类的属性
            Iterator properties = bean.elementIterator();
            while (properties.hasNext()) {
                Element element = (Element) properties.next();
                Iterator propertyAttributes = element.attributeIterator();
                while (propertyAttributes.hasNext()) {
                    Attribute attribute = (Attribute) propertyAttributes.next();
                    String attributeName = attribute.getName();
                    Object attributeData = attribute.getData();
                    propertyName.add(attributeName);
                    propertyData.add(attributeData);
                }
            }
            classList.add(clazz);
        }
        setBeanMap(idList, classList);
    }


    // 反射,依赖注入
    public Object[] getClass(List classList) throws Exception {
        Object[] objects = new Object[classList.size()];
        int i = 0;
        int j = 0;
        for (Class clazz : classList) {
            Object o = clazz.newInstance();
            Method[] methods = clazz.getDeclaredMethods();
            for (Method method : methods) {
                String methodName = method.getName();
                //System.out.println(methodName);
                if ("set".equals(methodName.substring(0, 3))) {
                    String name = propertyName.get(i);
                    Object data = propertyData.get(i);
                    String field = (String) data;
                    if (name.equals("name")) {
                        data = "set" + ((String) data).substring(0, 1).toUpperCase() + ((String) data).substring(1, ((String) data).length());
                    } else if (name.equals("value")) {

                    } else
                        continue;

                    String name1 = propertyName.get(i + 1);
                    Object data1 = propertyData.get(i + 1);

                    // 依赖注入
                    if (methodName.equals(data)) {
                        Field field1 = clazz.getDeclaredField(field);
                        Class type = field1.getType();
                        String typeName = type.getName();
                        if ("int".equals(typeName))
                            data1 = Integer.valueOf((String) data1);
                        method.invoke(o, data1);
                    }
                    i += 2;
                }
            }
            objects[j] = o;
            j++;
            //System.out.println(o);
        }
        return objects;

    }

    public void setBeanMap(List idList, List classList) throws Exception {
        map = new HashMap<>();
        Object[] objects = getClass(classList);
        for (int i = 0; i < objects.length; i++) {
            map.put(idList.get(i), objects[i]);
        }
    }

    public Object getBean(String beanName) {
        if (!map.isEmpty())
            return map.get(beanName);
        return null;
    }

    public Map getBeanMap() {
        return map;
    }


}
 
  

5、主类

package com.spring.xml;

import com.spring.xml.bean.Car;
import com.spring.xml.utils.XmlApplicationContext;
import java.util.Map;

/**
 * Hello world!
 */
public class App {
    public static void main(String[] args) {
        XmlApplicationContext context  = new XmlApplicationContext("applicationContext.xml");
        Car car = (Car)context.getBean("car");
        System.out.println(car);
        Map map = context.getBeanMap();
        System.out.println(map);
    }
}

6、结果

简单实现Spring IOC (单例模式)(解析XML方式)_第2张图片

你可能感兴趣的:(Spring,Java)