Spring5源码解析3-refresh方法初探
接上回分析完register(annotatedClasses);
后,现在来看一下refresh();
方法。
// new AnnotationConfigApplicationContext(AppConfig.class); 源码
public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
//调用默认无参构造器,里面有一大堆初始化逻辑
this();
//把传入的Class进行注册,Class既可以有@Configuration注解,也可以没有@Configuration注解
//怎么注册? 委托给了 org.springframework.context.annotation.AnnotatedBeanDefinitionReader.register 方法进行注册
// 传入Class 生成 BeanDefinition , 然后通过 注册到 BeanDefinitionRegistry
register(annotatedClasses);
//刷新容器上下文
refresh();
}
refresh方法
点开refresh();
方法,里面调用了超级多的方法,我们一个个来看。
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
//准备上下文,设置其启动日期和活动标志,执行属性源的初始化
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
//调用子类 refreshBeanFactory()方法
//获取 BeanFactory 实例 DefaultListableBeanFactory , DefaultListableBeanFactory 实现了 ConfigurableListableBeanFactory 接口
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
//配置 beanFactory 上下文
//1.添加 ApplicationContextAwareProcessor 和 ApplicationListenerDetector
//2.忽略部分类型的自动装配
//3.注册特殊的依赖类型,并使用相应的autowired值
//4.注册默认的environment beans
//5.设置environment beans
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
//留给子类去扩展的一个方法
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
onRefresh();
// Check for listener beans and register them.
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
finishRefresh();
} catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// Destroy already created singletons to avoid dangling resources.
destroyBeans();
// Reset 'active' flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
} finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
}
}
}
prepareRefresh();
prepareRefresh();
做的事情比较简单:准备上下文,设置其启动日期和活动标志,执行属性源的初始化。
protected void prepareRefresh() {
// Switch to active.
this.startupDate = System.currentTimeMillis();
this.closed.set(false);
this.active.set(true);
if (logger.isDebugEnabled()) {
if (logger.isTraceEnabled()) {
logger.trace("Refreshing " + this);
} else {
logger.debug("Refreshing " + getDisplayName());
}
}
// Initialize any placeholder property sources in the context environment.
//这是一个空方法,AnnotationConfigApplicationContext 并没有 Override 改方法
initPropertySources();
// Validate that all properties marked as required are resolvable:
// see ConfigurablePropertyResolver#setRequiredProperties
getEnvironment().validateRequiredProperties();
// Store pre-refresh ApplicationListeners...
if (this.earlyApplicationListeners == null) {
//默认情况下,earlyApplicationListeners 为 null
this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
} else {
// Reset local application listeners to pre-refresh state.
this.applicationListeners.clear();
this.applicationListeners.addAll(this.earlyApplicationListeners);
}
// Allow for the collection of early ApplicationEvents,
// to be published once the multicaster is available...
this.earlyApplicationEvents = new LinkedHashSet<>();
}
obtainFreshBeanFactory();
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
refreshBeanFactory();
return getBeanFactory();
}
refreshBeanFactory();
是一个抽象方法,它有两个具体是实现:
AnnotationConfigApplicationContext
继承 GenericApplicationContext
,所以很显然此处执行的应该是GenericApplicationContext
类中的方法。GenericApplicationContext
的refreshBeanFactory()
源码如下:
//GenericApplicationContext#refreshBeanFactory 源码
@Override
protected final void refreshBeanFactory() throws IllegalStateException {
if (!this.refreshed.compareAndSet(false, true)) {
throw new IllegalStateException(
"GenericApplicationContext does not support multiple refresh attempts: just call 'refresh' once");
}
this.beanFactory.setSerializationId(getId());
}
obtainFreshBeanFactory();
方法最后调用 getBeanFactory();
方法,并且返回ConfigurableListableBeanFactory
对象。
getBeanFactory();
,顾名思义就是获取BeanFactory
,Spring中使用的是 DefaultListableBeanFactory
,该类也同时实现了ConfigurableListableBeanFactory
接口。
prepareBeanFactory(beanFactory);
prepareBeanFactory(beanFactory);
源码比较简单:
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// Tell the internal bean factory to use the context's class loader etc.
beanFactory.setBeanClassLoader(getClassLoader());
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
// Configure the bean factory with context callbacks.
//增加 BeanPostProcessor 实例 ApplicationContextAwareProcessor
//ApplicationContextAwareProcessor 主要作用是对 Aware接口的支持,如果实现了相应的 Aware接口,则注入对应的资源
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
//默认情况下,只忽略BeanFactoryAware接口,现在新增忽略如下类型的自动装配
beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
// BeanFactory interface not registered as resolvable type in a plain factory.
// MessageSource registered (and found for autowiring) as a bean.
//注册自动装配规则,如果发现依赖特殊类型,就使用该指定值注入
beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
beanFactory.registerResolvableDependency(ResourceLoader.class, this);
beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
beanFactory.registerResolvableDependency(ApplicationContext.class, this);
// Register early post-processor for detecting inner beans as ApplicationListeners.
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
// Detect a LoadTimeWeaver and prepare for weaving, if found.
if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
// Set a temporary ClassLoader for type matching.
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
// Register default environment beans.
//注册默认的environment beans.
if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
// Environment
beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
}
if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
// System Properties
beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
}
if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
// System Environment
beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
}
}
ApplicationContextAwareProcessor
prepareBeanFactory(beanFactory);
方法中往beanFactory
中添加了一个ApplicationContextAwareProcessor
对象:beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
。
ApplicationContextAwareProcessor
类实现了BeanPostProcessor
接口,其中主要是 Override 了postProcessBeforeInitialization
方法,其作用主要是用来对 Aware
系列接口的支持,发现Bean
实现了Aware
系列接口,就调用其相应的方法,具体为哪些Aware
接口,请查看源码:
//ApplicationContextAwareProcessor#postProcessBeforeInitialization 源码
public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {
AccessControlContext acc = null;
if (System.getSecurityManager() != null &&
(bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware ||
bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware ||
bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware)) {
acc = this.applicationContext.getBeanFactory().getAccessControlContext();
}
if (acc != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
invokeAwareInterfaces(bean);
return null;
}, acc);
} else {
invokeAwareInterfaces(bean);
}
return bean;
}
private void invokeAwareInterfaces(Object bean) {
if (bean instanceof Aware) {
if (bean instanceof EnvironmentAware) {
((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());
}
if (bean instanceof EmbeddedValueResolverAware) {
((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.embeddedValueResolver);
}
if (bean instanceof ResourceLoaderAware) {
((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
}
if (bean instanceof ApplicationEventPublisherAware) {
((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);
}
if (bean instanceof MessageSourceAware) {
((MessageSourceAware) bean).setMessageSource(this.applicationContext);
}
if (bean instanceof ApplicationContextAware) {
((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
}
}
}
程序运行到这里,再看看一下Spring容器中有哪些数据:
6个
BeanDefinition
对象3 个单例
Bean
2 个
BeanPostProcessor
postProcessBeanFactory(beanFactory);
这是一个留给子类去拓展的空方法,AnnotationConfigApplicationContext
类中的该方法没有做任何事情。
未完待续......
源码学习笔记:https://github.com/shenjianeng/spring-code-study
欢迎关注公众号:
Spring5源码解析3-refresh方法初探的更多相关文章
- Spring5源码解析-Spring框架中的单例和原型bean
Spring5源码解析-Spring框架中的单例和原型bean 最近一直有问我单例和原型bean的一些原理性问题,这里就开一篇来说说的 通过Spring中的依赖注入极大方便了我们的开发.在xml通过& ...
- Spring5源码解析-论Spring DispatcherServlet的生命周期
Spring Web框架架构的主要部分是DispatcherServlet.也就是本文中重点介绍的对象. 在本文的第一部分中,我们将看到基于Spring的DispatcherServlet的主要概念: ...
- Spring源码解析之八finishBeanFactoryInitialization方法即初始化单例bean
Spring源码解析之八finishBeanFactoryInitialization方法即初始化单例bean 七千字长文深刻解读,Spirng中是如何初始化单例bean的,和面试中最常问的Sprin ...
- 多线程爬坑之路-Thread和Runable源码解析之基本方法的运用实例
前面的文章:多线程爬坑之路-学习多线程需要来了解哪些东西?(concurrent并发包的数据结构和线程池,Locks锁,Atomic原子类) 多线程爬坑之路-Thread和Runable源码解析 前面 ...
- [Java多线程]-Thread和Runable源码解析之基本方法的运用实例
前面的文章:多线程爬坑之路-学习多线程需要来了解哪些东西?(concurrent并发包的数据结构和线程池,Locks锁,Atomic原子类) 多线程爬坑之路-Thread和Runable源码解析 前面 ...
- Spring5源码解析_IOC之容器的基本实现
前言: 在分析源码之前,我们简单回顾一下SPring核心功能的简单使用: 容器的基本用法 Bean是Spring最核心的东西,Spring就像是一个大水桶,而Bean就是水桶中的水,水桶脱离了水就没有 ...
- 一文带你解读Spring5源码解析 IOC之开启Bean的加载,以及FactoryBean和BeanFactory的区别。
前言 通过往期的文章我们已经了解了Spring对XML配置文件的解析,将分析的信息组装成BeanDefinition,并将其保存到相应的BeanDefinitionRegistry中,至此Spring ...
- Spring5源码解析2-register方法注册配置类
接上回已经讲完了this()方法,现在来看register(annotatedClasses);方法. // new AnnotationConfigApplicationContext(AppCon ...
- Spring5源码解析4-refresh方法之invokeBeanFactoryPostProcessors
invokeBeanFactoryPostProcessors(beanFactory);方法源码如下: protected void invokeBeanFactoryPostProcessors( ...
随机推荐
- CodeForces - 534B-Covered Path+思路
CodeForces - 534B 题意:给定初始和末尾的速度,和最大加速度和总时间,求出走的最长路程: 我一开始以为代码写起来会很繁琐... #include <iostream> #i ...
- hdu6333 Harvest of Apples 离线+分块+组合数学(求组合数模板)
Problem B. Harvest of Apples Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 262144/262144 K ...
- codeforces 27 E. Number With The Given Amount Of Divisors(数论+dfs)
题目链接:http://codeforces.com/contest/27/problem/E 题意:问因数为n个的最小的数是多少. 题解:一般来说问到因数差不多都会想到素因子. 任意一个数x=(p1 ...
- PAT 天梯杯 L2-014 列车调度
火车站的列车调度铁轨的结构如下图所示. Figure 两端分别是一条入口(Entrance)轨道和一条出口(Exit)轨道,它们之间有N条平行的轨道.每趟列车从入口可以选择任意一条轨道进入,最后从出口 ...
- ubuntu下创建定时任务的两种方式及常见问题解决方案
创建定时任务的目的就是摆脱人为对程序重复性地运行. 0. 首先用下面的指令检查你是否安装crontab, crontab -l 如果本身就有的话,那么出现如下指令 LC_CTYPE="zh_ ...
- spring aop 的一个思考
问题: spring aop 默认使用jdk代理织入. 也就是我们常这样配置:<aop:aspectj-autoproxy /> 通过aop命名空间的<aop:aspectj-au ...
- 【第十篇】easyui-datagrid排序 (转)
本文体验datagrid的排序. □ 思路 当点击datagrid的标题,视图传递给Controller的Form Data类似这样:page=1&rows=10&sort=Custo ...
- group by语法
group by 用法解析 group by语法可以根据给定数据列的每个成员对查询结果进行分组统计,最终得到一个分组汇总表. SELECT子句中的列名必须为分组列或列函数.列函数对于GROUP BY子 ...
- python 虚拟环境下导入模块出现no matching modules 的解决办法
问题原因:pip版本过低 解决办法:升级pip 命令行为 python -m pip install -U pip
- CDH5.16.1离线集成Phoenix
1.安装环境 Centos 7.6 CDH 5.16.1 2.下载Phoenix所需的parcel包 3.上传parcel包到ClouderaManager server所在的节点上 /opt/clo ...