我是靠谱客的博主 舒心犀牛,最近开发中收集的这篇文章主要介绍简单实现Spring IOC (单例模式)(解析XML方式),觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

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

主要思路:

           1、解析xml文件

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

           3、根据类路径反射类

           4、注入属性信息

项目基本框架:

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

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

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.spring.xml</groupId>
  <artifactId>ioc</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>ioc</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
    <!--定义Spring版本号-->
    <org.springframework.version>4.3.7.RELEASE</org.springframework.version>
  </properties>

  <dependencies>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>dom4j</groupId>
      <artifactId>dom4j</artifactId>
      <version>1.6.1</version>
    </dependency>

    <!-- spring start -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-expression</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-instrument</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-instrument-tomcat</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jms</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-messaging</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-oxm</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc-portlet</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-websocket</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <!-- spring end -->
  </dependencies>

  <build>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.7.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.20.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

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

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="car" class="com.spring.xml.bean.Car">
        <property name="name" value="BMW"/>
        <property name="price" value="100"/>
    </bean>

    <bean id="car1" class="com.spring.xml.bean.Car">
        <property name="name" value="ChangCheng"/>
        <property name="price" value="101"/>
    </bean>
</beans>

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<String, Object> map = null;
    // 存放从xml解析出来的类的需要注入的属性名和属性值
    private List<String> propertyName = new ArrayList<>();
    private List<Object> 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<Class> classList = new ArrayList<>();
        List<String> 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<Class> 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<String> idList, List<Class> 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方式)的全部内容,希望文章能够帮你解决简单实现Spring IOC (单例模式)(解析XML方式)所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(41)

评论列表共有 0 条评论

立即
投稿
返回
顶部