实现一个简单的SpringIoc容器

1 篇文章 0 订阅
1 篇文章 0 订阅

学习过Spring的同学都知道,Spring框架的核心就是IoC和AOP。Spring可以理解为一个工厂,负责对象的创建和对象间关系的维护。IoC即控制反转,简单点说就是原来的对象是在要使用之前通过在代码里通过new 的方式创建出来的而IOC的思想则是由spring容器创建同一创建(配置文件中注册bean对象),在程序要使用到该对象的时候,自动注入。(spring默认在web容器启动的时候就创建了单例的对象)其最大的作用是减少了代码之间的耦合度。

     下面是我自己写的一个Spring框架,只是简单的模拟和实现了Spring的IoC容器功能。

1、首先定义一个应用上下文ApplicationContext,简单顶一个getBean方法

package com.wyh.study.spring.ioc;

/**
 * @Author: wuyaohua
 * @Description:
 * @Date: Created in 14:29 2018-08-22
 */
public interface ApplicationContext {

        Object getBean(String name);
}

2、定义SpringBean工厂ClassPathXMLApplicationContext 

package com.wyh.study.spring.ioc;

import org.apache.commons.collections.CollectionUtils;
import org.jdom.input.SAXBuilder;
import org.jdom.Document;
import org.jdom.JDOMException;
import org.jdom.Element;
import org.jdom.xpath.XPath;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URISyntaxException;
import java.util.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;


/**
 * @Author: wuyaohua
 * @Description:
 * @Date: Created in 14:27 2018-08-22
 */
public class ClassPathXMLApplicationContext implements ApplicationContext {
    private File file;
    private Map map = new HashMap();

    public ClassPathXMLApplicationContext(String config_file) {
        URL url = this.getClass().getClassLoader().getResource(config_file);

        try {
            file = new File(url.toURI());
            XMLParsing();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    private void XMLParsing() throws Exception {
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(file);
        XPath xpath = XPath.newInstance("//bean");
        List beans = xpath.selectNodes(doc);
        Iterator i = beans.iterator();
        while (i.hasNext()) {
            Element bean = (Element) i.next();
            String id = bean.getAttributeValue("id");
            String cls = bean.getAttributeValue("class");
            Object obj = Class.forName(cls).newInstance();
            Method[] method = obj.getClass().getDeclaredMethods();
            List<Element> list = bean.getChildren("property");
            for (Element el : list) {
                for (int n = 0; n < method.length; n++) {
                    String name = method[n].getName();
                    String temp = null;
                    if (name.startsWith("set")) {
                        temp = name.substring(3, name.length()).toLowerCase();
                        if (el.getAttribute("name") != null) {
                            if (temp.equals(el.getAttribute("name").getValue())) {
                                method[n].invoke(obj, el.getAttribute("value").getValue());
                            }
                        } else {
                            method[n].invoke(obj,map.get(el.getAttribute("ref").getValue()));
                        }
                    }
                }
            }
            map.put(id, obj);
        }
    }

    @Override
    public Object getBean(String name) {
        return map.get(name);
    }

}

3、编写Student类

package com.wyh.study.spring.ioc;

/**
 * @Author: wuyaohua
 * @Description:
 * @Date: Created in 14:27 2018-08-22
 */
public class Student {
    private String name;
    private String add;

    public void selfIntroDuction(){
        System.out.println("我的姓名是 " + name + " 我来自 " + add);

    }

    public String getName() {
        return name;
    }

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

    public String getAdd() {
        return add;
    }

    public void setAdd(String add) {
        this.add = add;
    }

}

4、编写StudentService,并在其中注入student类

package com.wyh.study.spring.ioc;

/**
 * @Author: wuyaohua
 * @Description:
 * @Date: Created in 14:27 2018-08-22
 */
public class StudentService {
    private  Student student;

    public Student getStudent() {
        return student;
    }

    public void setStudent(Student student) {
        this.student = student;
    }
}

5、编写applicationContext配置文件

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

<beans>
    <bean id="Student" class="com.wyh.study.spring.ioc.Student">
        <property name="name" value="WuYaoHua"/>
        <property name="add" value="China"/>
    </bean>

    <bean id="StudentService" class="com.wyh.study.spring.ioc.StudentService">
        <property ref="Student"/>
    </bean>
</beans>

6、测试类

package com.wyh.study.spring.ioc;

/**
 * @Author: wuyaohua
 * @Description:
 * @Date: Created in 14:31 2018-08-22
 */
public class Test {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXMLApplicationContext("applicationContext.xml");
        StudentService  stuServ = (StudentService) context.getBean("StudentService");
        stuServ.getStudent().selfIntroDuction();
    }

}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值