简单的理解Spring的实现过程,模拟了Spring的读取配置文件

项目结构

主要代码如下

User.java
1
2
3
4
5
6
public class User {
    private String username;
    private String password;
 
    // getter and setter ..
}
beans.xml 配置文件
1
2
3
4
5
6
<beans>
    <bean id="u" class="com.demo.dao.impl.UserDAOImpl" />
    <bean id="userService" class="com.demo.service.UserService">
        <property name="userDAO" bean="u" />
    </bean>
</beans>
ClassPathXmlApplicationContext.java 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/**
 * 管理器
 
 * @author jerome_s@qq.com
 */
public class ClassPathXmlApplicationContext implements BeanFactory {
 
    private Map<String, Object> beans = new HashMap<String, Object>();
 
    /**
     * 初始化配置文件
     * 模拟spring配置文件。模拟大的工厂,把东西都写到大的配置文件,通过代码读取xml文件模拟spring。
     
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public ClassPathXmlApplicationContext() throws Exception {
        System.out.println("ClassPathXmlApplicationContext init.");
        SAXBuilder sb = new SAXBuilder();
 
        Document doc = sb.build(this.getClass().getClassLoader().getResourceAsStream("beans.xml")); // 构造文档对象
        Element root = doc.getRootElement(); // 获取根元素HD
        List<Element> list = root.getChildren("bean");// 取名字为bean的所有元素
 
        // 循环每个bean
        for (int i = 0; i < list.size(); i++) {
            Element element = list.get(i);
            String id = element.getAttributeValue("id");
            String clazz = element.getAttributeValue("class");
            Object o = Class.forName(clazz).newInstance();
            System.out.println("ClassPathXmlApplicationContext bean's id = " + id);
            System.out.println("ClassPathXmlApplicationContext bean's class = " + clazz);
            beans.put(id, o);
 
            // 循环bean下的property
            for (Element propertyElement : (List<Element>) element.getChildren("property")) {
                // 调用 setUserDAO 设置 userDao的值
                String name = propertyElement.getAttributeValue("name"); // userDAO
                String bean = propertyElement.getAttributeValue("bean"); // u
                System.out.println("ClassPathXmlApplicationContext bean's property name = " + name);
                System.out.println("ClassPathXmlApplicationContext bean's property bean = " + bean);
 
                Object beanObject = beans.get(bean);// UserDAOImpl instance
 
                // userDAO -> setUserDao
                String methodName = "set" + name.substring(01).toUpperCase() + name.substring(1);
 
                Method m = o.getClass().getMethod(methodName, beanObject.getClass().getInterfaces()[0]);
                m.invoke(o, beanObject);
                System.out.println("ClassPathXmlApplicationContext bean's property invoke method " + methodName);
            }
 
            System.out.println("-------------------------");
        }
 
    }
 
    public Object getBean(String id) {
        return beans.get(id);
    }
 
}
UserService.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class UserService {
    private UserDAO userDAO;
 
    public void add(User user) {
        userDAO.save(user);
    }
 
    public UserDAO getUserDAO() {
        return userDAO;
    }
 
    public void setUserDAO(UserDAO userDAO) {
        this.userDAO = userDAO;
    }
}
UserDAOImpl.java
1
2
3
4
5
6
7
8
public class UserDAOImpl implements UserDAO {
 
    public void save(User user) {
        System.out.println("UserDAOImpl saved()");
        System.out.println("user.toString() = " + user.toString());
    }
 
}
运行结果如下
ClassPathXmlApplicationContext init.
ClassPathXmlApplicationContext bean's id = u
ClassPathXmlApplicationContext bean's class = com.demo.dao.impl.UserDAOImpl
-------------------------
ClassPathXmlApplicationContext bean's id = userService
ClassPathXmlApplicationContext bean's class = com.demo.service.UserService
ClassPathXmlApplicationContext bean's property name = userDAO
ClassPathXmlApplicationContext bean's property bean = u
ClassPathXmlApplicationContext bean's property invoke method name = setUserDAO
-------------------------
UserDAOImpl saved()
user.toString() = User [username=jerome, password=jeromepwd]


源码

简单模拟 Spring的更多相关文章

  1. (反射+内省机制的运用)简单模拟spring IoC容器的操作

    简单模拟spring IoC容器的操作[管理对象的创建.管理对象的依赖关系,例如属性设置] 实体类Hello package com.shan.hello; public class Hello { ...

  2. 一道面试题,简单模拟spring ioc

    自己实现的,程序写的土了点,很多情况没去考虑,主要是复习理解怎么使用反射来实现spring 的依赖注入. package dom4jtest; import java.lang.reflect.Inv ...

  3. 简单模拟Spring的注入

    主要就是读XML技术和反射技术. 在xml中读出相关配置信息,然后利用反射将其实例化为对象,并调用其构造方法,在实例化的过程中将属性注入实例. 实例化和属性注入这些操作都交给了框架,不再需要自己的去n ...

  4. 简单模拟Spring管理Bean对象

    1: 首先我们要利用dom4j进行xml的解析,将所有的bean的配置读取出来. 2:利用java的反射机制进行对象的实例化. 3: 直接获得对象 package cn.Junit.test; imp ...

  5. 【Spring系列】- 手写模拟Spring框架

    简单模拟Spring 生命不息,写作不止 继续踏上学习之路,学之分享笔记 总有一天我也能像各位大佬一样 一个有梦有戏的人 @怒放吧德德 分享学习心得,欢迎指正,大家一起学习成长! 前言 上次已经学习了 ...

  6. spring之mvc原理分析及简单模拟实现

    在之前的一篇博客中已经简单的实现了spring的IOC和DI功能,本文将在之前的基础上实现mvc功能. 一 什么是MVC MVC简单的说就是一种软件实现的设计模式,将整个系统进行分层,M(model ...

  7. java web学习总结(二十二) -------------------简单模拟SpringMVC

    在Spring MVC中,将一个普通的java类标注上Controller注解之后,再将类中的方法使用RequestMapping注解标注,那么这个普通的java类就够处理Web请求,示例代码如下: ...

  8. 工厂模式模拟Spring的bean加载过程

    一.前言    在日常的开发过程,经常使用或碰到的设计模式有代理.工厂.单例.反射模式等等.下面就对工厂模式模拟spring的bean加载过程进行解析,如果对工厂模式不熟悉的,具体可以先去学习一下工厂 ...

  9. 尚学堂Spring视频教程(一):模拟Spring

    Spring简单的说就是作为控制反转的容器,看这篇文章前需要先搞懂“控制反转和依赖注入“这个设计模式 我们先来模拟Spring,实现用户添加的功能,新建WEB项目”Spring_0100_Abstra ...

随机推荐

  1. js改变dom对象样式

    object.style.display = value; objcet对象必须是确定单个对象. 若以class名和标签名查找,需要指定对象集合中的第几个.

  2. VLAN之间单臂路由通信

    实验目的 理解单臂路由的应用场景 掌握路由器子接口的配置方法 掌握子接口封装VLAN的配置方法 理解单臂路由的工作原理 实验原理 单臂路由解决用户需要跨越VLAN实现通信的情况. 原理:通过一台路由器 ...

  3. ucsc 文件格式说明

    链接附带的是ucsc各种格式文件的说明,以后遇到新类型的文件可以先来这里看看! https://www.genome.ucsc.edu/FAQ/FAQformat.html

  4. URL重定向漏洞,python打造URL重定向漏洞检测脚本

    前言: 今天学习了重定向漏洞,这个漏洞比较好理解 漏洞名:URL重定向漏洞 威胁:低 漏洞的来源:开发者对head头做好对应的过滤和限制 例子: 有漏洞的网站:http://a.com/x.php?u ...

  5. 20160227.CCPP体系详解(0037天)

    程序片段(01):01.一对一模式.c+02.中介者模式.c+03.广播模式.c 内容概要:事件 ///01.一对一模式.c #include <stdio.h> #include < ...

  6. 《An Introduction to Signal Smoothing》译文

    最近在做数据平滑相关的工作,正好读到该篇博客,感觉不错,就翻译了一下.原链接:An Introduction to Signal Smoothing 信号平滑简介 噪声无处不在,不管是在采集手机游戏的 ...

  7. CocoaChina(总结)升级到xcode8遇到的问题及解决方案

    此总结由CocoaChina论坛版主wo709128079及广大坛友共同汇总.>>查看原帖 升级Xcode8已是必然,升级iOS 10的用户不能说大有人在,应该也不会少,楼主听说,如果不升 ...

  8. 用scheme重写Python的三大函数map reduce 和filter

    重写过程中,发现这种做法能加深对递归的理解,而且reduce还体现了函数式编程是如何通过参数传递来实现命令式编程中的状态改变的. (define (imap f x . y) (if (null? y ...

  9. 剑指Offer——完美+今日头条笔试题+知识点总结

    剑指Offer--完美+今日头条笔试题+知识点总结 情景回顾 时间:2016.9.28 16:00-18:00 19:00-21:00 地点:山东省网络环境智能计算技术重点实验室 事件:完美世界笔试 ...

  10. Gazebo機器人仿真學習探索筆記(三)機器人模型

    gazebo_models:https://bitbucket.org/osrf/gazebo_models 模型庫下載,可以參考如下命令: ~/Rob_Soft/Gazebo7$ hg clone ...