spring源码解析------xml方式解析加载bean

前言

最近有点顿悟,可能是面试的时候经历的多,感觉之前的学习有点浅尝辄止,对于底层的东西自己没有动手实现,现在把spring 以及后续的springboot进行一下梳理,我们首先解析源码然后手写实现过程,感受一下其中的趣味。
我将通过两种方式说明:

  • BeanFactory: bean组件
  • ApplicationContext:context组件,该组件扩展了bean组件,是我们常用的。

本文我们首先看看BeanFacory 是如何管理bean的。

一 效果

我们简单配置这样的xml 文件: 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="student" class="com.example.spring.Student" scope="singleton">
        <property name="nane" value="旭东"></property>
        <property name="age" value="23"></property>
    </bean>
    </bean>
</beans>

实体类就略了,测试下:

		BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("ApplicationContext.xml"));
        Student student = (Student) beanFactory.getBean("student");
        Student student1 = beanFactory.getBean(Student.class);

可以看到,XmlBeanFactory 解析先xml文件。

我们看下这个类的继承关系
在这里插入图片描述

二 具体的解析过程

1 new XmlBeanFactory(new ClassPathResource(“ApplicationContext.xml”));

我们进入里边

@Deprecated
public class XmlBeanFactory extends DefaultListableBeanFactory {
    private final XmlBeanDefinitionReader reader;

    public XmlBeanFactory(Resource resource) throws BeansException {
        this(resource, (BeanFactory)null);
    }

    public XmlBeanFactory(Resource resource, BeanFactory parentBeanFactory) throws BeansException {
        super(parentBeanFactory);
        this.reader = new XmlBeanDefinitionReader(this);
        this.reader.loadBeanDefinitions(resource);
    }
}

可以看到 XmlBeanFactory 继承了 DefaultListableBeanFactory ,然而解析xml用的却是自己定义的解析器 XmlBeanDefinitionReader ;

2 XmlBeanDefinitionReader 解析xml

loadBeanD

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值