[Spring source code analysis] Bean loading process overview (transfer)

 Reprinted from: https://www.cnblogs.com/xrq730/p/6285358.html

code entry

Before writing articles, I would start with a lot of long-winded and long-winded, and enter the [Spring source code analysis] section to directly cut to the topic.

Many friends may want to look at the Spring source code, but they don't know how to start. This is understandable: Java developers usually work on Java Web. For programmers, if a Web project uses Spring, just configure it It's just a configuration file. Spring's loading process is relatively opaque, and it's not easy to find the loaded code entry.

The following is a very simple piece of code that can be used as the entry point for Spring code loading:

1 ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");
 2 ac.getBean(XXX.class);

ClassPathXmlApplicationContext is used to load Spring configuration files under CLASSPATH. As you can see, Bean instances can already be obtained in the second line, so the first line must have completed the loading of all Bean instances, so ClassPathXmlApplicationContext can be used as the entry . In order to facilitate the reading of the code later, first give the inheritance relationship of the ClassPathXmlApplicationContext class:

The general inheritance relationship is as shown in the figure above. Due to the layout, the drawing is not continued. The ApplicationContext in the lower left corner should have another layer of inheritance relationship. The key point is that it is a sub-interface of BeanFactory.

Finally, I would like to state that the Spring version used in this article is 3.0.7, which is relatively old. The use of this version is purely because of the company's use.

 

ClassPathXmlApplicationContext stores content

In order to better understand ApplicationContext, take an instance of ClassPathXmlApplicationContext as an example, look at the content stored in it, deepen your understanding of ApplicationContext, and display it in table form:

object name Types of Use Attribution
configResources Resource[] Array of configuration file resource objects ClassPathXmlApplicationContext
configLocations String[] An array of configuration file strings, storing the configuration file path AbstractRefreshableConfigApplicationContext
beanFactory DefaultListableBeanFactory Bean factory used by the context AbstractRefreshableApplicationContext
beanFactoryMonitor Object Synchronization monitor used by the bean factory AbstractRefreshableApplicationContext
id String The unique Id used by the context to identify this ApplicationContext AbstractApplicationContext
parent ApplicationContext 父级ApplicationContext AbstractApplicationContext
beanFactoryPostProcessors List<BeanFactoryPostProcessor> Stores the BeanFactoryPostProcessor interface, an extension point provided by Spring AbstractApplicationContext
startupShutdownMonitor Object A monitor shared by the refresh method and the destroy method to avoid the simultaneous execution of the two methods AbstractApplicationContext
shutdownHook Thread A hook provided by Spring, the method in Thread will be run when the JVM stops executing AbstractApplicationContext
resourcePatternResolver ResourcePatternResolver The resource format parser used by the context AbstractApplicationContext
lifecycleProcessor LifecycleProcessor Lifecycle handler interface for managing bean lifecycle AbstractApplicationContext
messageSource Message Source An interface for internationalization AbstractApplicationContext
applicationEventMulticaster ApplicationEventMulticaster The event multicaster interface in the event management mechanism provided by Spring AbstractApplicationContext
applicationListeners Set<ApplicationListener> Application listeners in the event management mechanism provided by Spring AbstractApplicationContext

 

ClassPathXmlApplicationContext constructor

Take a look at the constructor of ClassPathXmlApplicationContext:

 1 public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
 2     this(new String[] {configLocation}, true, null);
 3 }
1 public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)
2         throws BeansException {
3 
4     super(parent);
5     setConfigLocations(configLocations);
6     if (refresh) {
7         refresh();
8     }
9 }

从第二段代码看,总共就做了三件事:

  1、super(parent)

    没什么太大的作用,设置一下父级ApplicationContext,这里是null

  2、setConfigLocations(configLocations)

    代码就不贴了,一看就知道,里面做了两件事情:

    (1)将指定的Spring配置文件的路径存储到本地

    (2)解析Spring配置文件路径中的${PlaceHolder}占位符,替换为系统变量中PlaceHolder对应的Value值,System本身就自带一些系统变量比如class.path、os.name、user.dir等,也可以通过System.setProperty()方法设置自己需要的系统变量

  3、refresh()

    这个就是整个Spring Bean加载的核心了,它是ClassPathXmlApplicationContext的父类AbstractApplicationContext的一个方法,顾名思义,用于刷新整个Spring上下文信息,定义了整个Spring上下文加载的流程。

 

refresh方法

上面已经说了,refresh()方法是整个Spring Bean加载的核心,因此看一下整个refresh()方法的定义:

 1 public void refresh() throws BeansException, IllegalStateException {
 2         synchronized (this.startupShutdownMonitor) {
 3             // Prepare this context for refreshing.
 4             prepareRefresh();
 5 
 6             // Tell the subclass to refresh the internal bean factory.
 7             ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
 8 
 9             // Prepare the bean factory for use in this context.
10             prepareBeanFactory(beanFactory);
11 
12             try {
13                 // Allows post-processing of the bean factory in context subclasses.
14                 postProcessBeanFactory(beanFactory);
15 
16                 // Invoke factory processors registered as beans in the context.
17                 invokeBeanFactoryPostProcessors(beanFactory);
18 
19                 // Register bean processors that intercept bean creation.
20                 registerBeanPostProcessors(beanFactory);
21 
22                 // Initialize message source for this context.
23                 initMessageSource();
24 
25                 // Initialize event multicaster for this context.
26                 initApplicationEventMulticaster();
27 
28                 // Initialize other special beans in specific context subclasses.
29                 onRefresh();
30 
31                 // Check for listener beans and register them.
32                 registerListeners();
33 
34                 // Instantiate all remaining (non-lazy-init) singletons.
35                 finishBeanFactoryInitialization(beanFactory);
36 
37                 // Last step: publish corresponding event.
38                 finishRefresh();
39             }
40 
41             catch (BeansException ex) {
42                 // Destroy already created singletons to avoid dangling resources.
43                 destroyBeans();
44 
45                 // Reset 'active' flag.
46                 cancelRefresh(ex);
47 
48                 // Propagate exception to caller.
49                 throw ex;
50             }
51         }
52     }

每个子方法的功能之后一点一点再分析,首先refresh()方法有几点是值得我们学习的:

  1、方法是加锁的,这么做的原因是避免多线程同时刷新Spring上下文

  2、尽管加锁可以看到是针对整个方法体的,但是没有在方法前加synchronized关键字,而使用了对象锁startUpShutdownMonitor,这样做有两个好处:

    (1)refresh()方法和close()方法都使用了startUpShutdownMonitor对象锁加锁,这就保证了在调用refresh()方法的时候无法调用close()方法,反之亦然,避免了冲突

    (2)另外一个好处不在这个方法中体现,但是提一下,使用对象锁可以减小了同步的范围,只对不能并发的代码块进行加锁,提高了整体代码运行的效率

  3、方法里面使用了每个子方法定义了整个refresh()方法的流程,使得整个方法流程清晰易懂。这点是非常值得学习的,一个方法里面几十行甚至上百行代码写在一起,在我看来会有三个显著的问题:

    (1)扩展性降低。反过来讲,假使把流程定义为方法,子类可以继承父类,可以根据需要重写方法

    (2)代码可读性差。很简单的道理,看代码的人是愿意看一段500行的代码,还是愿意看10段50行的代码?

    (3)代码可维护性差。这点和上面的类似但又有不同,可维护性差的意思是,一段几百行的代码,功能点不明确,不易后人修改,可能会导致“牵一发而动全身”

 

prepareRefresh方法

下面挨个看refresh方法中的子方法,首先是prepareRefresh方法,看一下源码:

 1 /**
 2  * Prepare this context for refreshing, setting its startup date and
 3  * active flag.
 4  */
 5 protected void prepareRefresh() {
 6     this.startupDate = System.currentTimeMillis();
 7         synchronized (this.activeMonitor) {
 8         this.active = true;
 9     }
10 
11     if (logger.isInfoEnabled()) {
12         logger.info("Refreshing " + this);
13     }
14 }

这个方法功能比较简单,顾名思义,准备刷新Spring上下文,其功能注释上写了:

1、设置一下刷新Spring上下文的开始时间

2、将active标识位设置为true

另外可以注意一下12行这句日志,这句日志打印了真正加载Spring上下文的Java类。

 

obtainFreshBeanFactory方法

obtainFreshBeanFactory方法的作用是获取刷新Spring上下文的Bean工厂,其代码实现为:

1 protected 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 }

其核心是第二行的refreshBeanFactory方法,这是一个抽象方法,有AbstractRefreshableApplicationContext和GenericApplicationContext这两个子类实现了这个方法,看一下上面ClassPathXmlApplicationContext的继承关系图即知,调用的应当是AbstractRefreshableApplicationContext中实现的refreshBeanFactory,其源码为:

protected final void refreshBeanFactory() throws BeansException {
    if (hasBeanFactory()) {
        destroyBeans();
        closeBeanFactory();
    }
    try {
        DefaultListableBeanFactory beanFactory = createBeanFactory();
        beanFactory.setSerializationId(getId());
        customizeBeanFactory(beanFactory);
        loadBeanDefinitions(beanFactory);
        synchronized (this.beanFactoryMonitor) {
            this.beanFactory = beanFactory;
        }
    }
    catch (IOException ex) {
        throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
    }
}

这段代码的核心是第7行,这行点出了DefaultListableBeanFactory这个类,这个类是构造Bean的核心类,这个类的功能会在下一篇文章中详细解读,首先给出DefaultListableBeanFactory的继承关系图:

AbstractAutowireCapableBeanFactory这个类的继承层次比较深,版面有限,就没有继续画下去了,本图基本上清楚地展示了DefaultListableBeanFactory的层次结构。

为了更清晰地说明DefaultListableBeanFactory的作用,列举一下DefaultListableBeanFactory中存储的一些重要对象及对象中的内容,DefaultListableBeanFactory基本就是操作这些对象,以表格形式说明:

 对象名 类  型  作    用 归属类
 aliasMap Map<String, String> 存储Bean名称->Bean别名映射关系   SimpleAliasRegistry
singletonObjects  Map<String, Object>  存储单例Bean名称->单例Bean实现映射关系 DefaultSingletonBeanRegistry 
 singletonFactories  Map<String, ObjectFactory> 存储Bean名称->ObjectFactory实现映射关系  DefaultSingletonBeanRegistry 
earlySingletonObjects   Map<String, Object> 存储Bean名称->预加载Bean实现映射关系    DefaultSingletonBeanRegistry 
registeredSingletons  Set<String>  存储注册过的Bean名  DefaultSingletonBeanRegistry 
singletonsCurrentlyInCreation  Set<String> 存储当前正在创建的Bean名    DefaultSingletonBeanRegistry  
 disposableBeans  Map<String, Object>

存储Bean名称->Disposable接口实现Bean实现映射关系  

   DefaultSingletonBeanRegistry   
 factoryBeanObjectCache  Map<String, Object> 存储Bean名称->FactoryBean接口Bean实现映射关系 FactoryBeanRegistrySupport 
propertyEditorRegistrars   Set<PropertyEditorRegistrar> 存储PropertyEditorRegistrar接口实现集合 AbstractBeanFactory 
 embeddedValueResolvers List<StringValueResolver>  存储StringValueResolver(字符串解析器)接口实现列表 AbstractBeanFactory 
beanPostProcessors  List<BeanPostProcessor>  存储 BeanPostProcessor接口实现列表 AbstractBeanFactory
mergedBeanDefinitions  Map<String, RootBeanDefinition>  存储Bean名称->合并过的根Bean定义映射关系  AbstractBeanFactory 
 alreadyCreated Set<String>  存储至少被创建过一次的Bean名集合   AbstractBeanFactory  
ignoredDependencyInterfaces  Set<Class>  存储不自动装配的接口Class对象集合  AbstractAutowireCapableBeanFactory 
 resolvableDependencies Map<Class, Object>  存储修正过的依赖映射关系  DefaultListableBeanFactory 
beanDefinitionMap  Map<String, BeanDefinition>  存储Bean名称-->Bean定义映射关系  DefaultListableBeanFactory  
beanDefinitionNames List<String> 存储Bean定义名称列表   DefaultListableBeanFactory  
================================================================================== 

我不能保证写的每个地方都是对的,但是至少能保证不复制、不黏贴,保证每一句话、每一行代码都经过了认真的推敲、仔细的斟酌。每一篇文章的背后,希望都能看到自己对于技术、对于生活的态度。

我相信乔布斯说的,只有那些疯狂到认为自己可以改变世界的人才能真正地改变世界。面对压力,我可以挑灯夜战、不眠不休;面对困难,我愿意迎难而上、永不退缩。

其实我想说的是,我只是一个程序员,这就是我现在纯粹人生的全部。

AbstractAutowireCapableBeanFactory这个类的继承层次比较深,版面有限,就没有继续画下去了,本图基本上清楚地展示了DefaultListableBeanFactory的层次结构。

为了更清晰地说明DefaultListableBeanFactory的作用,列举一下DefaultListableBeanFactory中存储的一些重要对象及对象中的内容,DefaultListableBeanFactory基本就是操作这些对象,以表格形式说明:

 对象名 类  型  作    用 归属类
 aliasMap Map<String, String> 存储Bean名称->Bean别名映射关系   SimpleAliasRegistry
singletonObjects  Map<String, Object>  存储单例Bean名称->单例Bean实现映射关系 DefaultSingletonBeanRegistry 
 singletonFactories  Map<String, ObjectFactory> 存储Bean名称->ObjectFactory实现映射关系  DefaultSingletonBeanRegistry 
earlySingletonObjects   Map<String, Object> 存储Bean名称->预加载Bean实现映射关系    DefaultSingletonBeanRegistry 
registeredSingletons  Set<String>  存储注册过的Bean名  DefaultSingletonBeanRegistry 
singletonsCurrentlyInCreation  Set<String> 存储当前正在创建的Bean名    DefaultSingletonBeanRegistry  
 disposableBeans  Map<String, Object>

存储Bean名称->Disposable接口实现Bean实现映射关系  

   DefaultSingletonBeanRegistry   
 factoryBeanObjectCache  Map<String, Object> 存储Bean名称->FactoryBean接口Bean实现映射关系 FactoryBeanRegistrySupport 
propertyEditorRegistrars   Set<PropertyEditorRegistrar> 存储PropertyEditorRegistrar接口实现集合 AbstractBeanFactory 
 embeddedValueResolvers List<StringValueResolver>  存储StringValueResolver(字符串解析器)接口实现列表 AbstractBeanFactory 
beanPostProcessors  List<BeanPostProcessor>  存储 BeanPostProcessor接口实现列表 AbstractBeanFactory
mergedBeanDefinitions  Map<String, RootBeanDefinition>  存储Bean名称->合并过的根Bean定义映射关系  AbstractBeanFactory 
 alreadyCreated Set<String>  存储至少被创建过一次的Bean名集合   AbstractBeanFactory  
ignoredDependencyInterfaces  Set<Class>  存储不自动装配的接口Class对象集合  AbstractAutowireCapableBeanFactory 
 resolvableDependencies Map<Class, Object>  存储修正过的依赖映射关系  DefaultListableBeanFactory 
beanDefinitionMap  Map<String, BeanDefinition>  存储Bean名称-->Bean定义映射关系  DefaultListableBeanFactory  
beanDefinitionNames List<String> 存储Bean定义名称列表   DefaultListableBeanFactory  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326204223&siteId=291194637