前言
最近有点顿悟,可能是面试的时候经历的多,感觉之前的学习有点浅尝辄止,对于底层的东西自己没有动手实现,现在把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