spring容器默认情况下,当服务启动时,解析配置文件,实例化文件中的所有类。

我们直接使用spring时,获取spring注入的bean是这样的,

ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");

MyService myService1 = (MyService) ctx.getBean("myService");

那下面我们模拟spring管理bean这个的过程,代码如下

1.         第一步,创建Javaproject,引入spring.jar

2.         创建spring.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-2.5.xsd">

</beans>

3.         创建接口MyService,只需要一个测试方法save

4.         创建实现类MyServiceImpl,控制台输出一句话

5.         创建一个自己的解析类MyClassPathXmlApplicationContext

主要是构造方法中的两步

     // 装载实例化bean

        private Map<String, Object> beanMap = new HashMap<String, Object>();

        // 装载配置文件的属性和值

        private List<MyBeans> beanlist = new ArrayList<MyBeans>();

        public MyClassPathXmlApplicationContext(String filename) {

               //第一步,解析spring配置文件

               readXml(filename);

               //第二步,通过反射,实例化所有注入bean

               initBeans();

        }

        /**

         * 通过反射机制,初始化配置文件中的bean

         */

        private void initBeans() {

               for (MyBeans bean : beanlist) {

                      try {

                             if (bean.getClassName() != null && !"".equals(bean.getClassName())) {

                                    beanMap.put(bean.getId(), Class.forName(bean.getClassName()).newInstance());

                             }

                      } catch (Exception e) {

                             e.printStackTrace();

                      }

               }

        }

        /**

         * 解析配置文件,把解析后的bean设置到实体中,并保持到list

         *

         * @param filename

         */

        private void readXml(String filename) {

               SAXReader reader = new SAXReader();

               Document doc = null;

               URL xmlpath = this.getClass().getClassLoader().getResource(filename);

               try {

                      Map<String, String> nsMap = new HashMap<String, String>();

                      nsMap.put("ns", "http://www.springframework.org/schema/beans");

                      doc = reader.read(xmlpath);

                      XPath xpath = doc.createXPath("//ns:beans//ns:bean");// 创建//ns:beans//ns:bean查询路径

                      xpath.setNamespaceURIs(nsMap);// 设置命名空间

                      List<Element> eles = xpath.selectNodes(doc);// 取得文档下所有节点

                      for (Element element : eles) {

                             String id = element.attributeValue("id");

                             String cn = element.attributeValue("class");

                             //自定义实体bean,保存配置文件中id和class

                             MyBeans beans = new MyBeans(id, cn);

                             beanlist.add(beans);

                      }

               } catch (Exception e) {

                      e.printStackTrace();

               }

        }

        public Object getBean(String beanId) {

               return beanMap.get(beanId);

        }

 6.         实体类

 package com.mooing.service;

 public class MyBeans {

        private String id;

        private String className;

        public MyBeans(String id, String className) {

               this.id = id;

               this.className = className;

        }

        public String getId() {

               return id;

        }

        public void setId(String id) {

               this.id = id;

        }

        public String getClassName() {

               return className;

        }

        public void setClassName(String className) {

               this.className = className;

        }

 }

7.         测试

       MyClassPathXmlApplicationContext ctx = new MyClassPathXmlApplicationContext("spring.xml");

               MyService myService = (MyService) ctx.getBean("myService");

                myService.save();

总结:

自定义代码同样可以得到使用spring容器实例化的效果,也就是说,实际spring实例化管理bean时,也是经过两大步:第一,服务启动解析配置文件,并保存配置文件中的元素;第二,实例化所有元素,并提供获取实例方法。

【Sping管理bean的原理】的更多相关文章

  1. (转)编码剖析Spring管理Bean的原理

    http://blog.csdn.net/yerenyuan_pku/article/details/52832434 在Spring的第一个案例中,我们已经知道了怎么将bean交给Spring容器进 ...

  2. 编码剖析Spring管理bean的原理

    project目录 MyClassPathXMLApplicationContext读取xml,以及实例化bean. 因为是一开始实例化配置文件所有bean,所以需要构造器完成这些工作. packag ...

  3. Spring、编码剖析Spring管理Bean的原理

    引入dom4j jar包 1.新建Person接口和PersonBean public interface PersonIService { public void helloSpring(); } ...

  4. Spring第三弹—–编码剖析Spring管理Bean的原理

    先附一下编写的Spring容器的执行结果: 代码如下: 模拟的Spring容器类:   1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 ...

  5. Spring中管理Bean以及解析XML

    Spring是分层的轻量级框架 以IoC(Inverse of Control 反转控制)和AOP(Aspect Oriented Programming 面向切面编程)为核心 应用Spring的好处 ...

  6. Spring是如何管理Bean

    容器是什么?spring中是如何体现的?一直有疑惑,这两天看了一下Spring管理bean的Demo,对于Spring中的容器有了简单的认识. 我们知道,容器是一个空间的概念,一般理解为可盛放物体的地 ...

  7. Sping中Bean配置的深入探讨

    一.p命名空间的使用 Spring 从 2.5 版本开始引入了一个新的 p 命名空间,可以通过 <bean> 元素属性的方式配置 Bean 的属性.使用 p 命名空间后,基于 XML 的配 ...

  8. Atitit 软件项目非法模块与功能的管理与  监狱管理的对比 原理与概论attilax总结

    Atitit 软件项目非法模块与功能的管理与  监狱管理的对比 原理与概论attilax总结 软件项目中的非法模块非法功能非法分子与人类中的非法分子很是相似,必须要建议不同的的约束管理标准化... 软 ...

  9. Spring4.0学习笔记(5) —— 管理bean的生命周期

    Spring IOC 容器可以管理Bean的生命周期,Spring允许在Bean生命周期的特定点执行定制的任务 Spring IOC 容器对Bean的生命周期进行管理的过程: 1.通过构造器或工厂方法 ...

随机推荐

  1. Sobel边缘检测

    Sobel算子:[-1  0  1 -2  0  2 -1  0  1] 用此算子与原图像做卷积,可以检测出垂直方向的边缘.算子作用在图像的第二列,结果是:200,200,200:作用在第三列,结果是 ...

  2. HDU 4089 Activation:概率dp + 迭代【手动消元】

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4089 题意: 有n个人在排队激活游戏,Tomato排在第m个. 每次队列中的第一个人去激活游戏,有可能 ...

  3. php深入浅出session

    1. session概念 0 2. http协议与状态保持 0 3. 理解cookie 0 4. php中session的生成机制 2 5. php中session的过期回收机制 3 6. php中s ...

  4. 初学Linux笔记

    自动获取IP地址的局域网中,用的是DHCP服务器

  5. 十九 Django框架,发送邮件

    全局配置settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' #发送邮件引擎 EMAIL_USE_TLS ...

  6. Chrome_01_点击 Google搜索结果在新的页面打开

    方法一:Ctrl + 左键 Chrome浏览器中,通过 Ctrl + 左键 ,是在新标签中打开的,通过 Shift + 左键 ,是在新窗口中打开的. 方法二: 1.登录 Google 2.进入下面的设 ...

  7. Oracle忘记用户名密码

    一.oracle 11g登录服务开启 成功安装Oracle 11g后,共有7个服务,这七个服务的含义分别为:1. Oracle ORCL VSS Writer Service:Oracle卷映射拷贝写 ...

  8. python中zip()函数基本用法

    zip()函数接受一系列可迭代对象作为参数,将不同对象中相对应的元素打包成一个元组(tuple),返回由这些元组组成的list列表,如果传入的参数的长度不等,则返回的list列表的长度和传入参数中 ...

  9. SQL Server DBA十大必备工具使生活轻松

    [IT168 技术]曾经和一些DBA和数据库开发人员交流时,问他们都用过一些什么样的DB方面的工具,大部分人除了SSMS和Profile之外,基本就没有使用过 其他工具了;诚然,SSMS和Profil ...

  10. Tangent space(切线空间)

    https://en.wikipedia.org/wiki/Frenet%E2%80%93Serret_formulas The tangent, normal, and binormal unit ...