实现一个简单的SpringIoc容器
发布日期:2022-02-09 20:39:11 浏览次数:11 分类:技术文章

本文共 4528 字,大约阅读时间需要 15 分钟。

学习过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
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配置文件

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();    }}

 

转载地址:https://blog.csdn.net/JohneyWu/article/details/81944427 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:手写一个简单的JAVA线程池
下一篇:使用JUC的forkjoin完成并发计算

发表评论

最新留言

路过按个爪印,很不错,赞一个!
[***.219.124.196]2024年04月07日 15时15分34秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章