概述
spring 版本6.0.12,阐述spring是如何通过xml文件配置的方式向容器中注册BeanDefinition
spring 源码准备
重点类与方法
正文之前,先将重要的类与方法标注,通过下面的详细可以快速定位到代码地点,打上断点进行调试
# 关键调试断点
org.springframework.context.support.ClassPathXmlApplicationContext#ClassPathXmlApplicationContext(java.lang.String[], boolean, org.springframework.context.ApplicationContext)
org.springframework.context.support.AbstractApplicationContext#refresh
org.springframework.context.support.AbstractRefreshableApplicationContext#refreshBeanFactory
org.springframework.context.support.AbstractXmlApplicationContext#loadBeanDefinitions(org.springframework.beans.factory.support.DefaultListableBeanFactory)
# 以下是非常重要的点
org.springframework.beans.factory.xml.XmlBeanDefinitionReader#loadBeanDefinitions(org.springframework.core.io.support.EncodedResource)
org.springframework.beans.factory.xml.XmlBeanDefinitionReader#doLoadBeanDefinitions
org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader#doRegisterBeanDefinitions
org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader#parseBeanDefinitions
org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader#parseDefaultElement
org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader#processBeanDefinition
源码调试
上图中相关代码依次展示
package org.springframework.my;
import org.springframework.stereotype.Component;
@Component
public class TestBean {
public void print() {
System.out.println("test bean method ...");
System.out.println("spring源码环境构建完成");
}
}
package org.springframework.test.my;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.my.TestBean;
public class IOCTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
TestBean bean = context.getBean(TestBean.class);
bean.print();
}
}
<?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="testBean" class="org.springframework.my.TestBean"/>
</beans>
先概括一下流程:1.加载xml文件,2.将xml转化为document对象3.将document转化成一个BeanDefinition
- 加载xml文件涉及到了spring 资源加载方式
- xml转化成document (这一块可以跳过,不重要)
- doc对象转化 (涉及bean空间的定义,后续有机会补充)
上面3点,看的时候可以选择性跳过
以下图片顺序及调试顺序(图片上有中文注释)
得到
通过重点类与方法调试点,可以快速打断点,spring xml方式注册bean的脉络就清楚了