作者 | 付政委
博客 | https://bugstack.cn
微信公众号:bugstack虫洞栈 | 博客:https://bugstack.cn 沉淀、分享、成长,专注于原创专题案例,以最易学习编程的方式分享知识,让自己和他人都能有所收获。目前已完成的专题有;Netty4.x实战专题案例、用Java实现JVM、基于JavaAgent的全链路监控、手写RPC框架、架构设计专题案例[Ing]等。 你用剑?、我用刀?,好的代码都很烧?,望你不吝出招?
往往简单的背后都有人为你承担着不简单,Spring 就是这样的家伙!而分析它的源码就像鬼吹灯,需要寻龙、点穴、分金、定位,最后往往受点伤(时间)、流点血(精力)、才能获得宝藏(成果)。
另外鉴于之前分析spring-mybatis、quartz,一篇写了将近2万字,内容过于又长又干,挖藏师好辛苦,看戏的也憋着肾,所以这次分析spring源码分块解读,便于理解、便于消化。
那么,这一篇就从 bean 的加载开始,从 xml 配置文件解析 bean 的定义,到注册到 Spring 的核心类 DefaultListableBeanFactory ,盗墓过程如下;
微信公众号:bugstack虫洞栈 & 盗墓
从上图可以看到从 xml 解析出 bean 到注册完成需要经历过8个核心类以及22个方法跳转流程,这也是本文后面需要重点分析的内容。好!那么就当为了你的钱程一起盗墓吧!
对于源码分析一定要单独列一个简单的工程,一针见血的搞你最需要的地方,模拟、验证、调试。现在这个案例工程还很简单,随着后面分析内容的增加,会不断的扩充。整体工程可以下载,可以关注公众号:bugstack虫洞栈 | 回复:源码分析
1itstack-demo-code-spring
2└── src
3 ├── main
4 │ ├── java
5 │ │ └── org.itstack.demo
6 │ │ └── UserService.java
7 │ └── resources
8 │ └── spring-config.xml
9 └── test
10 └── java
11 └── org.itstack.demo.test
12 └── ApiTest.java
整个 bean 注册过程核心功能包括;配置文件加载、工厂创建、XML解析、Bean定义、Bean注册,执行流程如下;
微信公众号:bugstack虫洞栈 & 盗墓
从上图的注册 bean 流程看到,核心类包括;
好!摸金分金定穴完事,搬山的搬山、卸岭的卸岭,开始搞!
UserService.java & 定义一个 bean,Spring 万物皆可 bean
1public class UserService {
2
3 public String queryUserInfo(Long userId) {
4 return "花花 id:" + userId;
5 }
6
7}
spring-config.xml & 在 xml 配置 bean 内容
1<?xml version="1.0" encoding="UTF-8"?>
2<beans xmlns="http://www.springframework.org/schema/beans"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
5 default-autowire="byName">
6
7 <bean id="userService" class="org.itstack.demo.UserService" scope="singleton"/>
8
9</beans>
ApiTest.java & 单元测试类
1@Test
2public void test_XmlBeanFactory() {
3 BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("spring-config.xml"));
4 UserService userService = beanFactory.getBean("userService", UserService.class);
5 logger.info("测试结果:{}", userService.queryUserInfo(1000L));
6}
7
8@Test
9public void test_ClassPathXmlApplicationContext() {
10 BeanFactory beanFactory = new ClassPathXmlApplicationContext("spring-config.xml");
11 UserService userService = beanFactory.getBean("userService", UserService.class);
12 logger.info("测试结果:{}", userService.queryUserInfo(1000L));
13}
两个单测方法都可以做结果输出,但是 XmlBeanFactory 已经标记为 @Deprecated 就是告诉我们这个墓穴啥也没有了,被盗过了,别看了。好!我们也不看他了,我们看现在推荐的2号墓 ClassPathXmlApplicationContext
如上不出意外正确结果如下;
123:34:24.699 [main] INFO org.itstack.demo.test.ApiTest - 测试结果:花花 id:1000
2
3Process finished with exit code 0
在整个 bean 的注册过程中,xml 解析是非常大的一块,也是非常重要的一块。如果顺着 bean 工厂初始化分析,那么一层层扒开,就像陈玉楼墓穴挖到一半,遇到大蜈蚣一样难缠。所以我们先把蜈蚣搞定!
1@Test
2public void test_DocumentLoader() throws Exception {
3
4 // 设置资源
5 EncodedResource encodedResource = new EncodedResource(new ClassPathResource("spring-config.xml"));
6
7 // 加载解析
8 InputSource inputSource = new InputSource(encodedResource.getResource().getInputStream());
9 DocumentLoader documentLoader = new DefaultDocumentLoader();
10 Document doc = documentLoader.loadDocument(inputSource, new ResourceEntityResolver(new PathMatchingResourcePatternResolver()), new DefaultHandler(), 3, false);
11
12 // 输出结果
13 Element root = doc.getDocumentElement();
14 NodeList nodeList = root.getChildNodes();
15 for (int i = 0; i < nodeList.getLength(); i++) {
16 Node node = nodeList.item(i);
17 if (!(node instanceof Element)) continue;
18 Element ele = (Element) node;
19 if (!"bean".equals(ele.getNodeName())) continue;
20 String id = ele.getAttribute("id");
21 String clazz = ele.getAttribute("class");
22 String scope = ele.getAttribute("scope");
23 logger.info("测试结果 beanName:{} beanClass:{} scope:{}", id, clazz, scope);
24 }
25
26}
可能初次看这段代码还是有点晕的,但这样提炼出来单独解决,至少给你一种有抓手的感觉。在 spring 解析 xml 时候首先是将配置资源交给 ClassPathResource ,再通过构造函数传递给 EncodedResource;
1private EncodedResource(Resource resource, String encoding, Charset charset) {
2 super();
3 Assert.notNull(resource, "Resource must not be null");
4 this.resource = resource;
5 this.encoding = encoding;
6 this.charset = charset;
7}
以上这个过程还是比较简单的,只是一个初始化过程。接下来是通过 Document 解析处理 xml 文件。这个过程是仿照 spring 创建时候需要的参数信息进行组装,如下;
1documentLoader.loadDocument(inputSource, new ResourceEntityResolver(new PathMatchingResourcePatternResolver()), new DefaultHandler(), 3, false);
2
3public Document loadDocument(InputSource inputSource, EntityResolver entityResolver,
4 ErrorHandler errorHandler, int validationMode, boolean namespaceAware) throws Exception {
5 DocumentBuilderFactory factory = createDocumentBuilderFactory(validationMode, namespaceAware);
6 if (logger.isDebugEnabled()) {
7 logger.debug("Using JAXP provider [" + factory.getClass().getName() + "]");
8 }
9 DocumentBuilder builder = createDocumentBuilder(factory, entityResolver, errorHandler);
10 return builder.parse(inputSource);
11}
通过上面的代码获取 org.w3c.dom.Document, Document 里面此时包含了所有 xml 的各个 Node 节点信息,最后输出节点内容,如下;
1Element root = doc.getDocumentElement();
2NodeList nodeList = root.getChildNodes();
好!测试一下,正常情况下,结果如下;
123:47:00.249 [main] INFO org.itstack.demo.test.ApiTest - 测试结果 beanName:userService beanClass:org.itstack.demo.UserService scope:singleton
2
3Process finished with exit code 0
可以看到的我们的 xml 配置内容已经完完整整的取出来了,接下来就交给 spring 进行处理了。红姑娘、鹧鸪哨、咱们出发!
ClassPathXmlApplicationContext.java & 截取部分代码
1public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)
2 throws BeansException {
3 super(parent);
4 setConfigLocations(configLocations);
5 if (refresh) {
6 refresh();
7 }
8}
AbstractApplicationContext.java & 部分代码截取
1@Override
2public void refresh() throws BeansException, IllegalStateException {
3 synchronized (this.startupShutdownMonitor) {
4 // 设置容器初始化
5 prepareRefresh();
6
7 // 让子类进行 BeanFactory 初始化,并且将 Bean 信息 转换为 BeanFinition,最后注册到容器中
8 // 注意,此时 Bean 还没有初始化,只是配置信息都提取出来了
9 ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
10
11 ...
12 }
13}
AbstractApplicationContext.java & 部分代码截取
1protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
2 refreshBeanFactory();
3 ConfigurableListableBeanFactory beanFactory = getBeanFactory();
4 if (logger.isDebugEnabled()) {
5 logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
6 }
7 return beanFactory;
8}
AbstractRefreshableApplicationContext.java & 部分代码截取
1protected final void refreshBeanFactory() throws BeansException {
2 if (hasBeanFactory()) {
3 destroyBeans();
4 closeBeanFactory();
5 }
6 try {
7 DefaultListableBeanFactory beanFactory = createBeanFactory();
8 beanFactory.setSerializationId(getId());
9 customizeBeanFactory(beanFactory);
10 loadBeanDefinitions(beanFactory);
11 synchronized (this.beanFactoryMonitor) {
12 this.beanFactory = beanFactory;
13 }
14 }
15 catch (IOException ex) {
16 throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
17 }
18}
AbstractXmlApplicationContext.java & 部分代码截取
1protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
2 // Create a new XmlBeanDefinitionReader for the given BeanFactory.
3 XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
4
5 // Configure the bean definition reader with this context's
6 // resource loading environment.
7 beanDefinitionReader.setEnvironment(this.getEnvironment());
8 beanDefinitionReader.setResourceLoader(this);
9 beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));
10
11 // Allow a subclass to provide custom initialization of the reader,
12 // then proceed with actually loading the bean definitions.
13 initBeanDefinitionReader(beanDefinitionReader);
14 loadBeanDefinitions(beanDefinitionReader);
15}
AbstractXmlApplicationContext.java & 部分代码截取
1protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
2 Resource[] configResources = getConfigResources();
3 if (configResources != null) {
4 reader.loadBeanDefinitions(configResources);
5 }
6 String[] configLocations = getConfigLocations();
7 if (configLocations != null) {
8 reader.loadBeanDefinitions(configLocations);
9 }
10}
AbstractBeanDefinitionReader.java & 部分代码截取
1public int loadBeanDefinitions(String... locations) throws BeanDefinitionStoreException {
2 Assert.notNull(locations, "Location array must not be null");
3 int counter = 0;
4 for (String location : locations) {
5 counter += loadBeanDefinitions(location);
6 }
7 return counter;
8}
AbstractBeanDefinitionReader.java & 部分代码截取
1public int loadBeanDefinitions(String location) throws BeanDefinitionStoreException {
2 return loadBeanDefinitions(location, null);
3}
AbstractBeanDefinitionReader.java & 部分代码截取
1public int loadBeanDefinitions(String location, Set<Resource> actualResources) throws BeanDefinitionStoreException {
2 ResourceLoader resourceLoader = getResourceLoader();
3 if (resourceLoader == null) {
4 throw new BeanDefinitionStoreException(
5 "Cannot import bean definitions from location [" + location + "]: no ResourceLoader available");
6 }
7
8 if (resourceLoader instanceof ResourcePatternResolver) {
9 // Resource pattern matching available.
10 try {
11 Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
12 int loadCount = loadBeanDefinitions(resources);
13 if (actualResources != null) {
14 for (Resource resource : resources) {
15 actualResources.add(resource);
16 }
17 }
18 if (logger.isDebugEnabled()) {
19 logger.debug("Loaded " + loadCount + " bean definitions from location pattern [" + location + "]");
20 }
21 return loadCount;
22 }
23 catch (IOException ex) {
24 throw new BeanDefinitionStoreException(
25 "Could not resolve bean definition resource pattern [" + location + "]", ex);
26 }
27 }
28 else {
29 // Can only load single resources by absolute URL.
30 Resource resource = resourceLoader.getResource(location);
31 int loadCount = loadBeanDefinitions(resource);
32 if (actualResources != null) {
33 actualResources.add(resource);
34 }
35 if (logger.isDebugEnabled()) {
36 logger.debug("Loaded " + loadCount + " bean definitions from location [" + location + "]");
37 }
38 return loadCount;
39 }
40}
XmlBeanDefinitionReader.java & 部分代码截取
1public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
2
3 // 判断验证
4 ...
5
6 try {
7 InputStream inputStream = encodedResource.getResource().getInputStream();
8 try {
9 InputSource inputSource = new InputSource(inputStream);
10 if (encodedResource.getEncoding() != null) {
11 inputSource.setEncoding(encodedResource.getEncoding());
12 }
13 return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
14 }
15 finally {
16 inputStream.close();
17 }
18 }
19 catch (IOException ex) {
20 throw new BeanDefinitionStoreException(
21 "IOException parsing XML document from " + encodedResource.getResource(), ex);
22 }
23 finally {
24 currentResources.remove(encodedResource);
25 if (currentResources.isEmpty()) {
26 this.resourcesCurrentlyBeingLoaded.remove();
27 }
28 }
29}
XmlBeanDefinitionReader.java & 部分代码截取
1protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
2 throws BeanDefinitionStoreException {
3 try {
4 Document doc = doLoadDocument(inputSource, resource);
5 return registerBeanDefinitions(doc, resource);
6 } catch(){}
7
8}
DefaultBeanDefinitionDocumentReader.java & 部分代码截取
1public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
2 this.readerContext = readerContext;
3 logger.debug("Loading bean definitions");
4 Element root = doc.getDocumentElement();
5 doRegisterBeanDefinitions(root);
6}
DefaultBeanDefinitionDocumentReader.java & 部分代码截取
1protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate deleg
2 if (delegate.isDefaultNamespace(root)) {
3 NodeList nl = root.getChildNodes();
4 for (int i = 0; i < nl.getLength(); i++) {
5 Node node = nl.item(i);
6 if (node instanceof Element) {
7 Element ele = (Element) node;
8 if (delegate.isDefaultNamespace(ele)) {
9 parseDefaultElement(ele, delegate);
10 }
11 else {
12 delegate.parseCustomElement(ele);
13 }
14 }
15 }
16 }
17 else {
18 delegate.parseCustomElement(root);
19 }
20}
DefaultBeanDefinitionDocumentReader.java & 部分代码截取
1private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
2 if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {
3 importBeanDefinitionResource(ele);
4 }
5 else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {
6 processAliasRegistration(ele);
7 }
8 else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {
9 processBeanDefinition(ele, delegate);
10 }
11 else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
12 // recurse
13 doRegisterBeanDefinitions(ele);
14 }
15}
DefaultBeanDefinitionDocumentReader.java & 部分代码截取
1protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
2 BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
3 if (bdHolder != null) {
4 bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
5 try {
6 // Register the final decorated instance.
7 BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
8 }
9 catch (BeanDefinitionStoreException ex) {
10 getReaderContext().error("Failed to register bean definition with name '" +
11 bdHolder.getBeanName() + "'", ele, ex);
12 }
13 // Send registration event.
14 getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
15 }
16}
BeanDefinitionReaderUtils.java & 部分代码截取
1public static void registerBeanDefinition(
2 BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)
3 throws BeanDefinitionStoreException {
4
5 // Register bean definition under primary name.
6 String beanName = definitionHolder.getBeanName();
7 registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());
8
9 // Register aliases for bean name, if any.
10 String[] aliases = definitionHolder.getAliases();
11 if (aliases != null) {
12 for (String alias : aliases) {
13 registry.registerAlias(beanName, alias);
14 }
15 }
16}
DefaultListableBeanFactory.java & 部分代码截取
1public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
2 throws BeanDefinitionStoreException {
3
4 Assert.hasText(beanName, "Bean name must not be empty");
5 Assert.notNull(beanDefinition, "BeanDefinition must not be null");
6
7 if (beanDefinition instanceof AbstractBeanDefinition) {
8 try {
9 ((AbstractBeanDefinition) beanDefinition).validate();
10 }
11 catch (BeanDefinitionValidationException ex) {
12 throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
13 "Validation of bean definition failed", ex);
14 }
15 }
16
17 BeanDefinition existingDefinition = this.beanDefinitionMap.get(beanName);
18 if (existingDefinition != null) {
19 ...
20 }
21 else {
22
23 ...
24
25 else {
26 // Still in startup registration phase
27 this.beanDefinitionMap.put(beanName, beanDefinition);
28 this.beanDefinitionNames.add(beanName);
29 this.manualSingletonNames.remove(beanName);
30 }
31 this.frozenBeanDefinitionNames = null;
32 }
33 if (existingDefinition != null || containsSingleton(beanName)) {
34 resetBeanDefinition(beanName);
35 }
36}
微信公众号:bugstack虫洞栈 & bean注册结果