Spring的容器创建过程
Spring容器的refresh()【创建刷新】
一、prepareRefresh()刷新前的预处理
1、initPropertySources()初始化一些属性设置;子类自定义个性化的属性设置方法;
2、getEnvironment().validateRequiredProperties();检验属性的合法等
3、earlyApplicationEvents= new LinkedHashSet<ApplicationEvent>();保存容器中的一些早期的事件;
二、obtainFreshBeanFactory():创建BeanFactory对象,并解析xml封装成BeanDefinition对象
1、refreshBeanFactory();刷新【创建】BeanFactory;
创建了一个this.beanFactory = new DefaultListableBeanFactory();
设置id;
2、getBeanFactory();返回刚才GenericApplicationContext创建的BeanFactory对象;
3、将创建的BeanFactory【DefaultListableBeanFactory】返回;
三、prepareBeanFactory(beanFactory):BeanFactory的预准备工作(BeanFactory进行一些设置属性)
1、设置BeanFactory的类加载器、支持表达式解析器...
2、添加部分BeanPostProcessor【ApplicationContextAwareProcessor】
3、设置忽略的自动装配的接口EnvironmentAware、EmbeddedValueResolverAware、xxx;
4、注册可以解析的自动装配;我们能直接在任何组件中自动注入:
BeanFactory、ResourceLoader、ApplicationEventPublisher、ApplicationContext
5、添加BeanPostProcessor【ApplicationListenerDetector】
6、添加编译时的AspectJ;
7、给BeanFactory中注册一些能用的组件;
environment【ConfigurableEnvironment】、
systemProperties【Map<String, Object>】、
systemEnvironment【Map<String, Object>】
四、postProcessBeanFactory(beanFactory):BeanFactory准备工作完成后,创建BeanFactory的处理器
1、子类通过重写这个方法来在BeanFactory创建并预准备完成以后做进一步的设置
---------------以上是BeanFactory的创建及预准备工作-----------------------------------------------
五、invokeBeanFactoryPostProcessors(beanFactory):【执行BeanFactory的处理器】
创建BeanDefinitionRegistryPostProcessor对象,执行postProcessor.postProcessBeanDefinitionRegistry(registry)方法
创建BeanFactoryPostProcessor对象,执行postProcessor.postProcessBeanFactory(beanFactory)
BeanFactoryPostProcessor:BeanFactory的后置处理器Bean工厂。在BeanFactory标准初始化之后执行的;
两个接口:BeanFactoryPostProcessor、BeanDefinitionRegistryPostProcessor
执行BeanFactoryPostProcessor的方法前;
先执行BeanDefinitionRegistryPostProcessor
1)、获取所有的BeanDefinitionRegistryPostProcessor;
2)、看先执行实现了PriorityOrdered优先级接口的BeanDefinitionRegistryPostProcessor
a、创建BeanDefinitionRegistryPostProcessor对象:beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class)
b、执行 postProcessor.postProcessBeanDefinitionRegistry(registry)
3)、在执行实现了Ordered顺序接口的BeanDefinitionRegistryPostProcessor;
a、创建BeanDefinitionRegistryPostProcessor对象:beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class)
b、执行 postProcessor.postProcessBeanDefinitionRegistry(registry)
4)、最后执行没有实现任何优先级或者是顺序接口的BeanDefinitionRegistryPostProcessors;
a、创建BeanDefinitionRegistryPostProcessor对象:beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class)
b、执行 postProcessor.postProcessBeanDefinitionRegistry(registry)
再执行BeanFactoryPostProcessor的方法
1)、获取所有的BeanFactoryPostProcessor
2)、看先执行实现了PriorityOrdered优先级接口的BeanFactoryPostProcessor、
a、创建BeanFactoryPostProcessor对象:beanFactory.getBean(ppName, BeanFactoryPostProcessor.class)
b、执行postProcessor.postProcessBeanFactory(beanFactory)
3)、在执行实现了Ordered顺序接口的BeanFactoryPostProcessor;
a、创建BeanFactoryPostProcessor对象:beanFactory.getBean(ppName, BeanFactoryPostProcessor.class)
b、执行postProcessor.postProcessBeanFactory(beanFactory)
4)、最后执行没有实现任何优先级或者是顺序接口的BeanFactoryPostProcessor;
a、创建BeanFactoryPostProcessor对象:beanFactory.getBean(ppName, BeanFactoryPostProcessor.class)
b、执行postProcessor.postProcessBeanFactory(beanFactory)
六、registerBeanPostProcessors(beanFactory):创建并注册BeanPostProcessor(Bean的处理器)【 intercept bean creation】
注释:BeanPostProcessor(Bean的处理器)有两个方法,postProcessBeforeInitialization(Bean处理器的前置方法)和 postProcessAfterInitialization(Bean处理器的后置方法)
不同接口类型的BeanPostProcessor;在Bean创建前后的执行时机是不一样的
BeanPostProcessor、
DestructionAwareBeanPostProcessor、
InstantiationAwareBeanPostProcessor、
SmartInstantiationAwareBeanPostProcessor、
MergedBeanDefinitionPostProcessor【internalPostProcessors】、
1)、获取所有的 BeanPostProcessor;后置处理器都默认可以通过PriorityOrdered、Ordered接口来执行优先级
2)、先注册PriorityOrdered优先级接口的BeanPostProcessor;
a、创建bean后置处理器 BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
b、把每一个BeanPostProcessor;添加到BeanFactory中
beanFactory.addBeanPostProcessor(postProcessor);
3)、再注册Ordered接口的
4)、最后注册没有实现任何优先级接口的
5)、最终注册MergedBeanDefinitionPostProcessor;
6)、注册一个ApplicationListenerDetector;来在Bean创建完成后检查是否是ApplicationListener,如果是
applicationContext.addApplicationListener((ApplicationListener<?>) bean);
七、initMessageSource():初始化MessageSource组件(做国际化功能;消息绑定,消息解析)
1)、获取BeanFactory
2)、看容器中是否有id为messageSource的,类型是MessageSource的组件
如果有赋值给messageSource,如果没有自己创建一个DelegatingMessageSource;
MessageSource:取出国际化配置文件中的某个key的值;能按照区域信息获取;
3)、把创建好的MessageSource注册在容器中,以后获取国际化配置文件的值的时候,可以自动注入MessageSource;
beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
MessageSource.getMessage(String code, Object[] args, String defaultMessage, Locale locale);
八、initApplicationEventMulticaster():初始化事件派发器
1)、获取BeanFactory
2)、从BeanFactory中获取applicationEventMulticaster的ApplicationEventMulticaster;
3)、如果上一步没有配置;创建一个SimpleApplicationEventMulticaster
4)、将创建的ApplicationEventMulticaster添加到BeanFactory中,以后其他组件直接自动注入
九、onRefresh():留给子容器(子类)
1)、子类重写这个方法,在容器刷新的时候可以自定义逻辑;
十、registerListeners():注册监听器
1)、从容器中拿到所有的ApplicationListener
2)、将每个监听器添加到事件派发器中;
getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
3)、派发之前步骤产生的事件;
十一、finishBeanFactoryInitialization(beanFactory):初始化所有剩下的单实例bean
beanFactory.preInstantiateSingletons();初始化后剩下的单实例bean
1)、获取容器中的所有Bean,依次进行初始化和创建对象
2)、获取Bean的定义信息;RootBeanDefinition
3)、Bean不是抽象的,是单实例的,是懒加载;
1)、判断是否是FactoryBean;是否是实现FactoryBean接口的Bean;
2)、不是工厂Bean。利用getBean(beanName);创建对象
0、getBean(beanName);DefaultListableBeanFactory#preInstantiateSingletons-->getBean(beanName);
1、doGetBean(name, null, null, false);
2、先获取缓存中保存的单实例Bean。如果能获取到说明这个Bean之前被创建过(所有创建过的单实例Bean都会被缓存起来)
Object sharedInstance = getSingleton(beanName);
从private final Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(256);获取的
3、缓存中获取不到,开始Bean的创建对象流程;
4、标记当前bean已经被创建, 防止其他线程重新创建 Bean;markBeanAsCreated(beanName);
5、获取Bean的定义信息;final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
6、【获取当前Bean依赖的其他Bean;如果有按照getBean(dep),优先把依赖的Bean先创建出来】
7、启动单实例Bean的创建流程;
1)、createBean(beanName, mbd, args);
sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
// 相当于创建了一个ObjectFactory类型的匿名内部类,去实现ObjectFactory接口中的getObject()方法
@Override
public Object getObject() throws BeansException {
try {
// 真正的Bean对象创建过程
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
// Explicitly remove instance from singleton cache: It might have been put there
// eagerly by the creation process, to allow for circular reference resolution.
// Also remove any beans that received a temporary reference to the bean.
destroySingleton(beanName);
throw ex;
}
}
});
等效于以下代码
ObjectFactory objectFactory = new ObjectFactory() {
@Override
public Object getObject() throws BeansException {
try {
return createBean(beanName, mbd, args);//创建代理对象,也可能是非代理
}
catch (BeansException ex) {
// Explicitly remove instance from singleton cache: It might have been put there
// eagerly by the creation process, to allow for circular reference resolution.
// Also remove any beans that received a temporary reference to the bean.
destroySingleton(beanName);
throw ex;
}
}
};
sharedInstance = getSingleton(beanName, objectFactory);
执行顺序为:getSingleton(beanName, objectFactory)---> singletonFactory.getObject() ----> createBean(beanName, mbd, args)
2)、Object bean = resolveBeforeInstantiation(beanName, mbdToUse);让BeanPostProcessor处理器先拦截bean返回proxy代理对象;
【InstantiationAwareBeanPostProcessor】:提前执行;
先触发:postProcessBeforeInstantiation();
如果有返回值:触发postProcessAfterInitialization()
3)、如果前面的InstantiationAwareBeanPostProcessor没有返回代理对象;调用4)
4)、Object beanInstance = doCreateBean(beanName, mbdToUse, args);创建Bean
1)、【创建Bean实例】;createBeanInstance(beanName, mbd, args);
利用工厂方法或者对象的构造器创建出Bean实例;
2)、applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);允许后置处理器修改bean的定义信息
调用MergedBeanDefinitionPostProcessor的postProcessMergedBeanDefinition(mbd, beanType, beanName);
3)、【Bean属性赋值】populateBean(beanName, mbd, instanceWrapper);
========= 赋值之前 =================================
1)、拿到InstantiationAwareBeanPostProcessor后置处理器;
postProcessAfterInstantiation();
2)、拿到InstantiationAwareBeanPostProcessor后置处理器;
postProcessPropertyValues();
========= 赋值之前 =================================
========= 赋值 ====================================
3)、应用Bean属性的值;为属性利用setter方法等进行赋值;
applyPropertyValues(beanName, mbd, bw, pvs);
4)、【Bean初始化】initializeBean(beanName, exposedObject, mbd);
1)、【执行Aware接口方法】invokeAwareMethods(beanName, bean); 校验该bean是否实现xxxAware接口(BeanNameAware、BeanClassLoaderAware、BeanFactoryAware等接口)对bean填充BeanName、BeanClassLoader、BeanFactory
2)、【初始化之前执行后置处理器的前置方法】applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
BeanPostProcessor.postProcessBeforeInitialization(); 是否生成bean的proxy代理对象返回
3)、【执行初始化方法】invokeInitMethods(beanName, wrappedBean, mbd);
1)、是否是InitializingBean接口的实现;执行接口规定的初始化;
2)、是否自定义初始化方法;
4)、【初始化之后执行后置处理器的后置方法】applyBeanPostProcessorsAfterInitialization,
BeanPostProcessor.postProcessAfterInitialization();是否生成bean的proxy代理对象返回
5)、将已初始化完成的bean,注册到销毁disposableBeans容器中;registerDisposableBeanIfNecessary(beanName, bean, mbd); 但并没有真正销毁;this.disposableBeans.put(beanName, bean),key为beanName ===== value为 disposableBeanAdapter【bean的销毁适配器】
5)、将创建的完整的Bean实例添加到singletonObjects一缓存中并删除二、三级缓存;
第1)步执行完return createBean(beanName, mbd, args)后,
重新回到DefaultSingletonBeanRegistry#getSingleton(String beanName, ObjectFactory<?> singletonFactory)方法
-->singletonObject = singletonFactory.getObject()-->return createBean(beanName, mbd, args)继续往下执行addSingleton(beanName, singletonObject)【将Bean添加到singletonObjects【一级缓存】,并删除earlySingletonObjects【二级缓存】和 singletonFactories【三级缓存】】
ioc容器就是这些Map;很多的Map里面保存了单实例Bean,环境信息.......;
所有Bean都利用getBean创建完成以后;
检查所有的Bean是否是SmartInitializingSingleton接口的;如果是;就执行afterSingletonsInstantiated();
十二、finishRefresh();完成刷新过程,通知声明周期处理器LifecycleProcessor刷新过程,同时发出ContextRefreshEvent通知别人
1)、initLifecycleProcessor();初始化和生命周期有关的后置处理器;LifecycleProcessor
默认从容器中找是否有lifecycleProcessor的组件【LifecycleProcessor】;如果没有new DefaultLifecycleProcessor();
加入到容器;
写一个LifecycleProcessor的实现类,可以在BeanFactory
void onRefresh();
void onClose();
2)、getLifecycleProcessor().onRefresh();
拿到前面定义的生命周期处理器(BeanFactory);回调onRefresh();
3)、publishEvent(new ContextRefreshedEvent(this));发布容器刷新完成事件;
4)、liveBeansView.registerApplicationContext(this);
-----------------总结-----------------------------------------------------------
1)、Spring容器在启动的时候,先会保存所有注册进来的Bean的定义信息;
1)、xml注册bean;<bean>
2)、注解注册Bean;@Service、@Component、@Bean、xxx
2)、Spring容器会合适的时机创建这些Bean
1)、用到这个bean的时候;利用getBean创建bean;创建好以后保存在容器中;
2)、统一创建剩下所有的bean的时候;finishBeanFactoryInitialization();
3)、后置处理器;BeanPostProcessor
1)、每一个bean创建完成,都会使用各种后置处理器进行处理;来增强bean的功能;
AutowiredAnnotationBeanPostProcessor:处理自动注入
AnnotationAwareAspectJAutoProxyCreator:来做AOP功能;
xxx....
增强的功能注解:
AsyncAnnotationBeanPostProcessor
....
4)、事件驱动模型;
ApplicationListener;事件监听;
ApplicationEventMulticaster;事件派发:
-----------------注意这段代码一与代码二是等效的-----------------------------------------------------------
代码一、
sharedInstance = getSingleton(beanName, () -> {
try {
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
// Explicitly remove instance from singleton cache: It might have been put there
// eagerly by the creation process, to allow for circular reference resolution.
// Also remove any beans that received a temporary reference to the bean.
destroySingleton(beanName);
throw ex;
}
});
代码二、
sharedInstance = getSingleton(beanName, () -> {
@verride
public object getObject throws BeansException{
try {
return createBean(beanName, mbd, args);
}catch (BeansException ex) {
// Explicitly remove instance from singleton cache: It might have been put there
// eagerly by the creation process, to allow for circular reference resolution.
// Also remove any beans that received a temporary reference to the bean.
destroySingleton(beanName);
throw ex;
}
}
})
Spring的容器创建过程的更多相关文章
- Spring IOC容器创建bean过程浅析
1. 背景 Spring框架本身非常庞大,源码阅读可以从Spring IOC容器的实现开始一点点了解.然而即便是IOC容器,代码仍然是非常多,短时间内全部精读完并不现实 本文分析比较浅,而完整的IOC ...
- Spring源码解析 – AnnotationConfigApplicationContext容器创建过程
Spring在BeanFactory基础上提供了一些列具体容器的实现,其中AnnotationConfigApplicationContext是一个用来管理注解bean的容器,从AnnotationC ...
- Spring MVC 学习 -- 创建过程
Spring MVC 学习 -- 创建过程 Spring MVC我们使用的时候会在web.xml中配置 <servlet> <servlet-name>SpringMVC< ...
- SpringMVC——DispatcherServlet的IoC容器(Web应用的IoC容器的子容器)创建过程
在上一篇<Spring--Web应用中的IoC容器创建(WebApplicationContext根应用上下文的创建过程)>中说到了Web应用中的IoC容器创建过程.这一篇主要讲Sprin ...
- Spring 源码(11)Spring Bean 的创建过程(2)
Spring Bean 的创建过程介绍了FactoryBean 的创建方式,那么接下来介绍不是FactoryBean的创建方式,在创建过程中,又会分为单例的Bean的创建,原型类型的Bean的创建等. ...
- Spring 源码(12)Spring Bean 的创建过程(3)
继续上一篇Spring Bean的创建过程的解读,上一篇介绍了Spring在创建过程中doGetBean方法,在执行过程中会调用getSingleton方法并且设置一个lambda表达式,这个lamb ...
- spring的bean创建过程
Spring的bean创建过程 步骤 执行过程 描述 1 ThreadLocal.set bean创建之前将beanName的一些属性放进ThreadLocal,避免多线程创建bean导致问题,并发创 ...
- Spring 源码(13)Spring Bean 的创建过程(4)
Spring Bean的创建过程非常的复杂,上一篇重点介绍了Spring在创建Bean的过程中,使用InstantiationBeanPostProcessor进行提前创建Bean,我们可以通过CGL ...
- spring bean的创建过程
spring的核心容器包括:core.beans.context.express language四个模块.所以对于一个简单的spring工程,最基本的就是依赖以下三个jar包即可: <depe ...
- 0003 - 基于xml的Spring Bean 的创建过程
一.目录 前言 创建 Bean 容器 加载 Bean 定义 创建 Bean Spring Bean 创建过程中的设计模式 总结 二.前言 2.1 Spring 使用配置 ApplicationCont ...
随机推荐
- Redis持久化(RDB、AOF)
为什么要持久化 Redis是内存数据库,如果不将内存中的数据库状态保存到磁盘中,那么一旦服务器进程退出,服务器的数据库状态就会消失(即断电即失).为了保证数据不丢失,我们需要将内存中的数据存储到磁盘, ...
- Overleaf使用技巧
插入图片 %插入图片% \begin{figure} \centering %居中% \resizebox{0.8\hsize}{!}{\includegraphics[clip=true]{Imag ...
- 从生活案例理解滑动窗口最大值:一个超直观的思路讲解|LeetCode 239 滑动窗口最大值
LeetCode 239 滑动窗口最大值 点此看全部题解 LeetCode必刷100题:一份来自面试官的算法地图(题解持续更新中) 更多干货,请关注公众号[忍者算法],回复[刷题清单]获取完整题解目录 ...
- “天翼云息壤杯”高校AI大赛云南赛区启动!
11月19日,首届全国"天翼云息壤杯"高校AI大赛云南赛区启动仪式在昆明理工大学举行.本次赛事由中国电信云南公司(以下简称"云南电信")和云南省计算机学会智能计 ...
- JMeter中使用嵌套变量方法
JMeter中使用嵌套变量方法 在使用JMeter进行接口测试时,经常遇到需要动态生成变量名并引用其值的情况.在JMeter中,嵌套变量的使用可以帮助我们实现这一目标.本文将详细介绍如何在JMeter ...
- [阿里DIN] 模型保存,加载和使用
[阿里DIN] 模型保存,加载和使用 0x00 摘要 Deep Interest Network(DIN)是阿里妈妈精准定向检索及基础算法团队在2017年6月提出的.其针对电子商务领域(e-comme ...
- 多线程之lamda表达式
代码简化过程 public class TestLambda1 { //3.静态内部类 static class Like2 implements ILike{ ...
- 如何训练LLM“思考”(像o1和DeepSeek-R1一样, 高级推理模型解析
2024年9月,OpenAI发布了它的o1模型,该模型基于大规模强化学习训练,赋予了它"高级推理"能力.不幸的是,他们是如何做到这一点的细节从未被公开披露.然而,今天,DeepSe ...
- Tensorflow 安装和测试(Anaconda4.7.10+windows10)
一. 软件下载 二. 配置相关 1. 修改 Jupyter notebook 默认工作路径 (1)打开 Anaconda Prompt ,输入 jupyter notebook --generate- ...
- Vue实现企业微信扫码登录
Vue实现企业微信扫码登录 企业微信扫码登录原理 构建企业微信登录二维码 获取访问令牌access_token 请求方式:GET(HTTPS)请求URL:https://qyapi.wei ...