文章目录
- 【README】
- 【1】spring容器初始化及bean实例化步骤列表
- 【2】spring容器初始化源码
- 【2.1】容器初始化主要步骤总结:
- 【2.2】容器初始化详细步骤源码分析
- 【3】bean实例化源码
- 【3.1】bean实例化主要步骤总结(非常重要)
- 【3.1.1】 bean生命周期(bean创建与初始化及销毁步骤)
- 【3.2】bean实例化详细步骤源码分析
- 【4】容器刷新收尾工作
- 【4.1】容器刷新收尾工作主要步骤总结:
- 【4.2】容器刷新收尾工作详细步骤源码分析
【README】
1)本文使用了spring-6.1.10制品库;
2)本文使用AnnotationConfigApplicationContext容器类型(注解配置应用容器), 基于java配置构建spring应用,没有xml配置;
3)基于spring构建应用系统分为2个阶段(或者狭义理解为spring容器启动过程分为2个阶段):
- 容器初始化阶段:
- 实例化容器,BeanDefinition读取器,类路径扫描器;
- 准备环境,包括注册属性bean(如os环境变量,jvm系统变量)到容器;
- 注册BeanFactory后置处理器并触发其后置处理方法,包括触发BeanDefinition注册后置处理器(使用扫描器与读取器读取并注册BeanDefinition到容器),触发BeanFactory后置处理器(如增强配置类);
- 注册Bean后置处理器到容器(用户自定义的Bean后置处理器);
- 注册消息源MessageSource到容器,用于国际化;
- 注册应用事件多播器到容器,用于发布spring各阶段事件;
- 注册应用监听器到容器,用于监听spring事件;
- bean实例化阶段:大致思想是根据BeanDefinition实例化bean;
4)补充:
- 实例化:就是创建或new的意思;
- 初始化:可以简单理解为设置属性,装配依赖bean;
5)spring容器构建应用系统示例,参见 spring源码01-spring容器启动流程概述
【1】spring容器初始化及bean实例化步骤列表
1)调用 AbstractApplicationContext#refresh()方法初始化容器,如下。
- 第1-10步是spring容器初始化代码逻辑; 参见章节【2】;
- 第11步bean实例化代码逻辑【最重要】(可以认为容器初始化的目的是bean实例化); 参见章节【3】;
- 第12步是容器属性收尾代码逻辑; 参见章节【4】;
【AbstractApplicationContext】
public void refresh() throws BeansException, IllegalStateException {this.startupShutdownLock.lock();try {this.startupShutdownThread = Thread.currentThread();StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");// 1 刷新容器的准备工作,包括初始化属性源,并校验属性,保存应用监听器; // Prepare this context for refreshing. prepareRefresh();// 2 默认实现:获取最新容器,包括把容器hashcode赋值给BeanFactory的序列化id// 也可以由子类来刷新内部BeanFactory// Tell the subclass to refresh the internal bean factory.ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();// 3 初始化BeanFactory // Prepare the bean factory for use in this context.prepareBeanFactory(beanFactory);try {// 4 protected方法,允许子类自行定义BeanFactory的后置处理逻辑 // Allows post-processing of the bean factory in context subclasses.postProcessBeanFactory(beanFactory);StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");// 5 触发BeanFacotry后置处理器// Invoke factory processors registered as beans in the context.invokeBeanFactoryPostProcessors(beanFactory);// 6 注册Bean后置处理器// Register bean processors that intercept bean creation.registerBeanPostProcessors(beanFactory);beanPostProcess.end();// 7 初始化消息源 ,用于国际化 // Initialize message source for this context.initMessageSource();// 8 初始化应用事件多播器 // Initialize event multicaster for this context.initApplicationEventMulticaster();// 9 子类可以重写的模板方法,以添加特定于上下文的刷新工作。在实例化单例之前,在初始化特殊 bean 时调用;// Initialize other special beans in specific context subclasses.onRefresh();// 10 注册监听器,包括应用事件多播器// Check for listener beans and register them.registerListeners();// 11 实例化所有剩余的单例bean// Instantiate all remaining (non-lazy-init) singletons.finishBeanFactoryInitialization(beanFactory);// 12 容器刷新的收尾工作,包括清空缓存,注册生命周期处理器并执行其onRefresh(),发布ContextRefreshedEvent事件;// Last step: publish corresponding event.finishRefresh();}catch (RuntimeException | Error ex ) { // 异常1: 销毁bean// Destroy already created singletons to avoid dangling resources.destroyBeans();// Reset 'active' flag.cancelRefresh(ex);// Propagate exception to caller.throw ex;}finally {contextRefresh.end();}}finally {this.startupShutdownThread = null;this.startupShutdownLock.unlock();}
}
【2】spring容器初始化源码
0)AbstractApplicationContext#refresh()方法步骤如【1】所示,本节主要关注第1步到第10步;
【2.1】容器初始化主要步骤总结:
1)容器初始化主要步骤总结:
- 步骤1)容器初始化;【prepareRefresh()】
- 初始化属性源,替换属性占位符 , 保存应用监听器;
- 步骤2) 获取最新BeanFactory; 【obtainFreshBeanFactory()】
- 步骤3)初始化BeanFactory; 【prepareBeanFactory(beanFactory)】
- 新增资源编辑器注册器-ResourceEditorRegistrar , 新增Bean后置处理器ApplicationContextAwareProcessor,ApplicationListenerDetector; 忽略依赖接口, 注册可处理器依赖
- 步骤4)允许子类自行定义BeanFactory的后置处理逻辑;【postProcessBeanFactory(beanFactory),子类容器可以重写】
- 步骤5)触发BeanFactory后置处理器; 【invokeBeanFactoryPostProcessors(beanFactory)】
- 触发BeanDefinitionRegistry后置处理器;(BeanFactory后置处理器的特殊类型) ;
- 触发BeanFactory后置处理器;
- 步骤6)注册Bean后置处理器; 【registerBeanPostProcessors(beanFactory)】
- 包括CommonAnnotationBeanPostProcessor, AutowiredAnnotationBeanPostProcessor ;
- 步骤7) 初始化消息源DelegatingMessageSource(),用于国际化;【initMessageSource()】
- 步骤8) 初始化应用事件多播器,类型为=SimpleApplicationEventMulticaster; 【initApplicationEventMulticaster()】
- 步骤9) 子类可以重写的模板方法,以添加特定于上下文的刷新工作。在实例化单例之前,在初始化特殊 bean 时调用;【onRefresh()】
- 步骤10) 注册监听器; 【registerListeners()】
【2.2】容器初始化详细步骤源码分析
1)调用prepareRefresh方法,初始化容器; 初始化属性源, 保存应用监听器-ApplicationListener;
protected void prepareRefresh() {// Switch to active.this.startupDate = System.currentTimeMillis();this.closed.set(false);this.active.set(true);// 日志 // 初始化属性源,替换属性占位符 // Initialize any placeholder property sources in the context environment.initPropertySources();// 校验属性 getEnvironment().validateRequiredProperties();if (this.earlyApplicationListeners == null) {// 保存应用监听器 this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);}else {this.applicationListeners.clear();this.applicationListeners.addAll(this.earlyApplicationListeners);}this.earlyApplicationEvents = new LinkedHashSet<>();
}
2)调用obtainFreshBeanFactory()获取最新BeanFactory;(ApplicationContext继承BeanFactory,可以理解为ApplicationContext为spring容器,BeanFactory是基础容器)
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {refreshBeanFactory();return getBeanFactory();}
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");}// 把id复制给BeanFactory的序列化idthis.beanFactory.setSerializationId(getId());}
3)调用 prepareBeanFactory(beanFactory) 初始化BeanFactory;
包括 新增资源编辑器注册器-ResourceEditorRegistrar , 新增Bean后置处理器ApplicationContextAwareProcessor,ApplicationListenerDetector; 忽略依赖接口, 注册可处理器依赖;
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()));// 新增资源编辑器注册器-ResourceEditorRegistrarbeanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment())); // Configure the bean factory with context callbacks.beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));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.ignoreDependencyInterface(ApplicationStartupAware.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 (!NativeDetector.inNativeImage() && 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. // 注册环境变量bean, 包括 environment, systemProperties, systemEnvironment,applicationStartu if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());}if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());}if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());}if (!beanFactory.containsLocalBean(APPLICATION_STARTUP_BEAN_NAME)) {beanFactory.registerSingleton(APPLICATION_STARTUP_BEAN_NAME, getApplicationStartup());}}
4)postProcessBeanFactory():默认为空,允许子类自行定义BeanFactory的后置处理逻辑
5)invokeBeanFactoryPostProcessors():触发BeanFactory后置处理器;
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());// Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime// (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)if (!NativeDetector.inNativeImage() && beanFactory.getTempClassLoader() == null &&beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));}}
【PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());】
- 5.1)触发BeanDefinitionRegistry后置处理器,调用postProcessBeanDefinitionRegistry方法,注册BeanDefinition ;
- 触发实现了PriorityOrdered(优先级排序接口)的BeanDefinitionRegistry后置处理器(如ConfigurationClassPostProcessor,读取配置类中的BeanDefinition);
- 触发实现了Ordered(排序接口)的BeanDefinitionRegistry后置处理器
- 触发剩余的BeanDefinitionRegistry后置处理器;
- BeanDefinitionRegistry后置处理器也是一种BeanFactory后置处理器,触发其postProcessBeanFactory的方法;
- 5.2)触发BeanFactory后置处理器,调用postProcessBeanFactory方法;
- 触发实现了PriorityOrdered接口的BeanFactory后置处理器;
- 触发实现了Ordered接口的BeanFactory后置处理器
- 触发剩余BeanFactory后置处理器 ;
public static void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) { // Invoke BeanDefinitionRegistryPostProcessors first, if any.Set<String> processedBeans = new HashSet<>();if (beanFactory instanceof BeanDefinitionRegistry registry) {List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {if (postProcessor instanceof BeanDefinitionRegistryPostProcessor registryProcessor) {registryProcessor.postProcessBeanDefinitionRegistry(registry);registryProcessors.add(registryProcessor);}else {regularPostProcessors.add(postProcessor);}}// Do not initialize FactoryBeans here: We need to leave all regular beans// uninitialized to let the bean factory post-processors apply to them!// Separate between BeanDefinitionRegistryPostProcessors that implement// PriorityOrdered, Ordered, and the rest.List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();// 1 触发实现了PriorityOrdered(优先级排序接口)的BeanDefinition注册后置处理器(如ConfigurationClassPostProcessor)String[] postProcessorNames =beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);for (String ppName : postProcessorNames) {if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));processedBeans.add(ppName);}}sortPostProcessors(currentRegistryProcessors, beanFactory);registryProcessors.addAll(currentRegistryProcessors);// 1.1 触发执行invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());currentRegistryProcessors.clear();// 2 触发实现了Ordered(排序接口)的BeanDefinition注册后置处理器postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);for (String ppName : postProcessorNames) {if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));processedBeans.add(ppName);}}sortPostProcessors(currentRegistryProcessors, beanFactory);registryProcessors.addAll(currentRegistryProcessors);// 2.1 触发执行 invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());currentRegistryProcessors.clear();// 3 触发剩余的BeanDefinition注册后置处理器boolean reiterate = true;while (reiterate) {reiterate = false;postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);for (String ppName : postProcessorNames) {if (!processedBeans.contains(ppName)) {currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));processedBeans.add(ppName);reiterate = true;}}sortPostProcessors(currentRegistryProcessors, beanFactory);registryProcessors.addAll(currentRegistryProcessors);// 3.1 触发执行 invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());currentRegistryProcessors.clear();}// 4 触发BeanDefinitionRegistryPostProcessor-postProcessBeanFactory的方法invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);}else {// Invoke factory processors registered with the context instance.invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);}// Do not initialize FactoryBeans here: We need to leave all regular beans// uninitialized to let the bean factory post-processors apply to them!String[] postProcessorNames =beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,// Ordered, and the rest.List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();List<String> orderedPostProcessorNames = new ArrayList<>();List<String> nonOrderedPostProcessorNames = new ArrayList<>();for (String ppName : postProcessorNames) {if (processedBeans.contains(ppName)) {// skip - already processed in first phase above}else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));}else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {orderedPostProcessorNames.add(ppName);}else {nonOrderedPostProcessorNames.add(ppName);}}sortPostProcessors(priorityOrderedPostProcessors, beanFactory);// 触发实现了PriorityOrdered接口的BeanFactory后置处理器invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());for (String postProcessorName : orderedPostProcessorNames) {orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));}sortPostProcessors(orderedPostProcessors, beanFactory);// 触发实现了Ordered接口的BeanFactory后置处理器invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);// Finally, invoke all other BeanFactoryPostProcessors.List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());for (String postProcessorName : nonOrderedPostProcessorNames) {nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));}// 触发剩余BeanFactory后置处理器 invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);beanFactory.clearMetadataCache();}
5.1)【PostProcessorRegistrationDelegate】invokeBeanDefinitionRegistryPostProcessors() -触发BeanDefinition注册后置处理器,调用其postProcessBeanDefinitionRegistry方法-后置处理BeanDefinition注册方法;
private static void invokeBeanDefinitionRegistryPostProcessors(Collection<? extends BeanDefinitionRegistryPostProcessor> postProcessors, BeanDefinitionRegistry registry, ApplicationStartup applicationStartup) {for (BeanDefinitionRegistryPostProcessor postProcessor : postProcessors) {StartupStep postProcessBeanDefRegistry = applicationStartup.start("spring.context.beandef-registry.post-process").tag("postProcessor", postProcessor::toString);postProcessor.postProcessBeanDefinitionRegistry(registry);postProcessBeanDefRegistry.end();}
}
5.1.1)【调用BeanDefinitionRegistryPostProcessor的postProcessBeanFactory()方法】 触发BeanDefinitionRegistryPostProcessor后置处理器,调用postProcessBeanFactory方法; 即BeanDefinitionRegistryPostProcessor 也是一种BeanFactory后置处理器 ;
private static void invokeBeanFactoryPostProcessors(Collection<? extends BeanFactoryPostProcessor> postProcessors, ConfigurableListableBeanFactory beanFactory) {for (BeanFactoryPostProcessor postProcessor : postProcessors) {StartupStep postProcessBeanFactory = beanFactory.getApplicationStartup().start("spring.context.bean-factory.post-process").tag("postProcessor", postProcessor::toString);// 执行BeanFactory后置处理器的后置处理方法postProcessor.postProcessBeanFactory(beanFactory); postProcessBeanFactory.end();}
}
5.2)触发BeanFactory后置处理器,调用postProcessBeanFactory方法
private static void invokeBeanFactoryPostProcessors(Collection<? extends BeanFactoryPostProcessor> postProcessors, ConfigurableListableBeanFactory beanFactory) {for (BeanFactoryPostProcessor postProcessor : postProcessors) {StartupStep postProcessBeanFactory = beanFactory.getApplicationStartup().start("spring.context.bean-factory.post-process").tag("postProcessor", postProcessor::toString);postProcessor.postProcessBeanFactory(beanFactory);postProcessBeanFactory.end();}
}
6)调用registerBeanPostProcessors(beanFactory); 注册Bean后置处理器 ;
【AbstractApplicationContext】
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
}
【PostProcessorRegistrationDelegate】registerBeanPostProcessors(),注册Bean后置处理器
public static void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) { String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, postProcessorNames, beanProcessorTargetCount));// Separate between BeanPostProcessors that implement PriorityOrdered,// Ordered, and the rest.List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();List<String> orderedPostProcessorNames = new ArrayList<>();List<String> nonOrderedPostProcessorNames = new ArrayList<>();for (String ppName : postProcessorNames) {if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);priorityOrderedPostProcessors.add(pp);if (pp instanceof MergedBeanDefinitionPostProcessor) {internalPostProcessors.add(pp);}}else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {orderedPostProcessorNames.add(ppName);}else {nonOrderedPostProcessorNames.add(ppName);}}// 注册实现PriorityOrdered接口的Bean后置处理器 sortPostProcessors(priorityOrderedPostProcessors, beanFactory);registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);// 注册实现Ordered接口的Bean后置处理器 List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());for (String ppName : orderedPostProcessorNames) {BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);orderedPostProcessors.add(pp);if (pp instanceof MergedBeanDefinitionPostProcessor) {internalPostProcessors.add(pp);}}sortPostProcessors(orderedPostProcessors, beanFactory);registerBeanPostProcessors(beanFactory, orderedPostProcessors);// 注册剩余的Bean后置处理器 List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());for (String ppName : nonOrderedPostProcessorNames) {BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);nonOrderedPostProcessors.add(pp);if (pp instanceof MergedBeanDefinitionPostProcessor) {internalPostProcessors.add(pp);}}registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);// 最后注册所有内部Bean后置处理器 sortPostProcessors(internalPostProcessors, beanFactory);registerBeanPostProcessors(beanFactory, internalPostProcessors);// Re-register post-processor for detecting inner beans as ApplicationListeners,// moving it to the end of the processor chain (for picking up proxies etc).// 新增ApplicationListenerDetector 这种Bean后置处理器 beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext)); }
【补充】内部Bean后置处理器-internalPostProcessors如下:
0 = {CommonAnnotationBeanPostProcessor@2306}
1 = {AutowiredAnnotationBeanPostProcessor@2307}
7)调用 initMessageSource(): 初始化消息源DelegatingMessageSource(),用于国际化;
【AbstractApplicationContext】
protected void initMessageSource() {ConfigurableListableBeanFactory beanFactory = getBeanFactory();if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);// Make MessageSource aware of parent MessageSource.if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource hms &&hms.getParentMessageSource() == null) {// Only set parent context as parent MessageSource if no parent MessageSource// registered already.hms.setParentMessageSource(getInternalParentMessageSource());}if (logger.isTraceEnabled()) {logger.trace("Using MessageSource [" + this.messageSource + "]");}}else {// Use empty MessageSource to be able to accept getMessage calls.// 实例化消息源,并注册到容器 DelegatingMessageSource dms = new DelegatingMessageSource();dms.setParentMessageSource(getInternalParentMessageSource());this.messageSource = dms;beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);if (logger.isTraceEnabled()) {logger.trace("No '" + MESSAGE_SOURCE_BEAN_NAME + "' bean, using [" + this.messageSource + "]");}}
}
8)调用initApplicationEventMulticaster();初始化应用事件多播器,类型为=SimpleApplicationEventMulticaster;
protected void initApplicationEventMulticaster() {ConfigurableListableBeanFactory beanFactory = getBeanFactory();if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {this.applicationEventMulticaster =beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);if (logger.isTraceEnabled()) {logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");}}else {// 这个分支 ,注册应用事件多播器this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);// 日志... }}
9)调用onRefresh(); 默认空;protected方法,子类可以重写的模板方法,以添加特定于上下文的刷新工作。在实例化单例之前,在初始化特殊 bean 时调用;
10)调用registerListeners()注册监听器,类型=ApplicationListener;
protected void registerListeners() {// Register statically specified listeners first.for (ApplicationListener<?> listener : getApplicationListeners()) {getApplicationEventMulticaster().addApplicationListener(listener);}// Do not initialize FactoryBeans here: We need to leave all regular beans// uninitialized to let post-processors apply to them!String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);for (String listenerBeanName : listenerBeanNames) {getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);}// Publish early application events now that we finally have a multicaster...Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;this.earlyApplicationEvents = null;if (!CollectionUtils.isEmpty(earlyEventsToProcess)) {for (ApplicationEvent earlyEvent : earlyEventsToProcess) {// 发布事件 getApplicationEventMulticaster().multicastEvent(earlyEvent);}}
}
【3】bean实例化源码
1)AbstractApplicationContext#refresh()方法的第11步;大致思想: 根据BeanDefinition实例化bean ;
【3.1】bean实例化主要步骤总结(非常重要)
1)bean实例化主要步骤总结(详细步骤如3.1所示)【非常重要,常见spring面试题】 :
- 步骤1) 实例化bean; (instantiateBean方法, 使用BeanDefinition+反射技术,工具方法-BeanUtils.instantiateClass)
- 步骤2) 填充bean属性;(populateBean方法,如Autowire自动装配依赖,属性变量替换);
- 步骤3) 初始化bean; (initializeBean方法)
- 调用Aware装配方法; (如BeanNameAware,BeanClassLoaderAware, BeanFactoryAware)
- 用BeanPostProcessor的初始化前置方法; (postProcessBeforeInitialization方法)
- 调用初始化方法() ; (调用InitializingBean#afterPropertiesSet方法,调用配置的init方法)
- 调用BeanPostProcessor的初始化后置方法; (postProcessAfterInitialization方法)
- 步骤4)注册可销毁bean;
- 调用registerDisposableBeanIfNecessary(), 可销毁bean=DisposableBean ;
- 步骤5) 调用SmartInitializingSingleton敏捷初始化单例的afterSingletonsInstantiated()
- 若bean实现SmartInitializingSingleton接口;
【3.1.1】 bean生命周期(bean创建与初始化及销毁步骤)
【3.2】bean实例化详细步骤源码分析
1) 由JavaBasedContainerUsingSeveralJavaConfigMain可知,context.refresh()刷新容器就是根据BeanDefinition实例化bean;
2)context.refresh()如下:
【AbstractApplicationContext】
public void refresh() throws BeansException, IllegalStateException {this.startupShutdownLock.lock();try {this.startupShutdownThread = Thread.currentThread();StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");// 1 初始化容器,包括初始化属性源,并校验属性,保存应用监听器; prepareRefresh();// 2 默认实现:获取最新容器,包括把容器hashcode赋值给BeanFactory的序列化id// 也可以由子类重写方法来刷新内部BeanFactoryConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();// 3 初始化BeanFactory prepareBeanFactory(beanFactory);try {// 4 默认空;也可以由子类自行定义BeanFactory的后置处理逻辑 postProcessBeanFactory(beanFactory);StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");// 5 触发BeanFacotry后置处理器invokeBeanFactoryPostProcessors(beanFactory);// 6 注册Bean后置处理器,拦截bean创建过程registerBeanPostProcessors(beanFactory);beanPostProcess.end();// 7 初始化消息源 ,用于国际化 initMessageSource();// 8 初始化应用事件多播器 initApplicationEventMulticaster();// 9 默认空,子类可以重写方法,以添加特定于上下文的刷新工作。在实例化单例之前,在初始化特殊 bean 时调用;onRefresh();// 10 注册监听器,包括应用事件多播器registerListeners();// 11 实例化所有剩余的单例bean 【核心方法】 // Instantiate all remaining (non-lazy-init) singletons.finishBeanFactoryInitialization(beanFactory);// 12 容器刷新的收尾工作,包括清空缓存,注册生命周期处理器并执行其onRefresh(),发布ContextRefreshedEvent事件;finishRefresh();}catch (RuntimeException | Error ex ) { // 异常1: 销毁bean// Destroy already created singletons to avoid dangling resources.destroyBeans(); // Reset 'active' flag.cancelRefresh(ex); // Propagate exception to caller.throw ex;}finally {contextRefresh.end();}}
}
本节主要关注第11步-finishBeanFactoryInitialization()-实例化所有剩余的单例bean ;
3)finishBeanFactoryInitialization(beanFactory);// 实例化所有剩余的单例bean(部分公共bean已经被实例化了,但业务bean在这一步被实例化)
接着调用 beanFactory.preInstantiateSingletons(); 预先实例化单例bean; beanFactory类型=DefaultListableBeanFactory;
【DefaultListableBeanFactory】 预先实例化单例bean
public void preInstantiateSingletons() throws BeansException {if (this.logger.isTraceEnabled()) {this.logger.trace("Pre-instantiating singletons in " + this);}List<String> beanNames = new ArrayList(this.beanDefinitionNames);Iterator var2 = beanNames.iterator();String beanName;while(var2.hasNext()) {beanName = (String)var2.next();RootBeanDefinition bd = this.getMergedLocalBeanDefinition(beanName);if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {if (this.isFactoryBean(beanName)) { // 是否工厂bean Object bean = this.getBean("&" + beanName);if (bean instanceof SmartFactoryBean) {SmartFactoryBean<?> smartFactoryBean = (SmartFactoryBean)bean;if (smartFactoryBean.isEagerInit()) {this.getBean(beanName);}}} else { this.getBean(beanName); // 尝试获取bean,若bean不存在,则实例化bean 【核心方法】 }}}var2 = beanNames.iterator();while(var2.hasNext()) {beanName = (String)var2.next();Object singletonInstance = this.getSingleton(beanName);// 是否SmartInitializingSingleton-敏捷初始化单例if (singletonInstance instanceof SmartInitializingSingleton smartSingleton) { StartupStep smartInitialize = this.getApplicationStartup().start("spring.beans.smart-initialize").tag("beanName", beanName);// 调用敏捷初始化单例回调方法-afterSingletonsInstantiated()smartSingleton.afterSingletonsInstantiated(); smartInitialize.end();}}
}
4)this.getBean(beanName); // 尝试获取bean,若bean不存在,则实例化bean ; 接着调用AbstractBeanFactory#doGetBean()方法获取bean;
【AbstractBeanFactory】
protected <T> T doGetBean(String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly) throws BeansException {String beanName = this.transformedBeanName(name);RootBeanDefinition mbd = this.getMergedLocalBeanDefinition(beanName);// 获取bean定义 // ... if (mbd.isSingleton()) { // 若bean为单例 sharedInstance = this.getSingleton(beanName, () -> { // 获取单例bean try {return this.createBean(beanName, mbd, args); // 创建bean方法} catch (BeansException var5) {this.destroySingleton(beanName);throw var5;}});beanInstance = this.getObjectForBeanInstance(sharedInstance, name, beanName, mbd);} // ...}
5)接着调用getSingleton() 方法
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {synchronized(this.singletonObjects) {Object singletonObject = this.singletonObjects.get(beanName);if (singletonObject == null) {if (this.singletonsCurrentlyInDestruction) {throw new BeanCreationNotAllowedException(beanName, "日志信息...)");}// 打印日志...// 事前校验是否可以创建beanName对应的bean(是否被排除在外)this.beforeSingletonCreation(beanName); boolean newSingleton = false;boolean recordSuppressedExceptions = this.suppressedExceptions == null;if (recordSuppressedExceptions) {this.suppressedExceptions = new LinkedHashSet();}try {// 通过单例工厂获取单例bean对象,singletonFactory参见第6步。singletonObject = singletonFactory.getObject();newSingleton = true;} catch (IllegalStateException var16) {singletonObject = this.singletonObjects.get(beanName);if (singletonObject == null) {throw var16;}} catch (BeanCreationException var17) {// 抛出异常} finally {if (recordSuppressedExceptions) {this.suppressedExceptions = null;}this.afterSingletonCreation(beanName);}if (newSingleton) {this.addSingleton(beanName, singletonObject);}}return singletonObject;}}
6)【singletonFactory】单例工厂的lambda表达式; 调用createBean()方法
() -> {try {return this.createBean(beanName, mbd, args);} catch (BeansException var5) {this.destroySingleton(beanName);throw var5;}
}
7)调用AbstractAutowireCapableBeanFactory#createBean()方法,创建bean:
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException {// 日志... RootBeanDefinition mbdToUse = mbd; // 获取BeanDefinitionClass<?> resolvedClass = this.resolveBeanClass(mbd, beanName, new Class[0]); Object beanInstance;try { // 判断是否存在实例化装配Bean后置处理器列表;// 若有则调用其postProcessBeforeInstantiation(),如果该方法实际创建了单例bean(至少存在1个Bean后置处理器),则直接返回;beanInstance = this.resolveBeforeInstantiation(beanName, mbdToUse);if (beanInstance != null) {return beanInstance;}} catch (Throwable var10) {// 抛出异常;}try {// 使用BeanDefinition创建Bean beanInstance = this.doCreateBean(beanName, mbdToUse, args);return beanInstance;} catch (ImplicitlyAppearedSingletonException | BeanCreationException var7) {throw var7;} catch (Throwable var8) {// 抛出异常...}}
【resolveBeforeInstantiation】实例化前解析;若存在实例化AwareBean后置处理器,则调用其postProcessBeforeInstantiation方法 【不存在InstantiationAwareBeanPostProcessor;即返回bean=null 】
protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {Object bean = null;if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {// 若存在实例化装配Bean后置处理器,则调用其postProcessBeforeInstantiation方法,// 若postProcessBeforeInstantiation方法返回不为null,则调用其postProcessAfterInitializationif (!mbd.isSynthetic() && this.hasInstantiationAwareBeanPostProcessors()) {Class<?> targetType = this.determineTargetType(beanName, mbd);if (targetType != null) {bean = this.applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);if (bean != null) {bean = this.applyBeanPostProcessorsAfterInitialization(bean, beanName);}}}mbd.beforeInstantiationResolved = bean != null;}return bean;
}
【BeanPostProcessorCache】bean后置处理器缓存 ;包括实例化AwareBean后置处理器-InstantiationAwareBeanPostProcessor ;
static class BeanPostProcessorCache {final List<InstantiationAwareBeanPostProcessor> instantiationAware = new ArrayList();final List<SmartInstantiationAwareBeanPostProcessor> smartInstantiationAware = new ArrayList();final List<DestructionAwareBeanPostProcessor> destructionAware = new ArrayList();final List<MergedBeanDefinitionPostProcessor> mergedDefinition = new ArrayList();BeanPostProcessorCache() {}
}
8)AbstractAutowireCapableBeanFactory.doCreateBean(beanName, mbdToUse, args):使用BeanDefinition创建Bean
protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException {BeanWrapper instanceWrapper = null;if (mbd.isSingleton()) {// 从缓存获取bean实例包裹对象instanceWrapper = (BeanWrapper)this.factoryBeanInstanceCache.remove(beanName);}if (instanceWrapper == null) {// 获取为null,则创建Bean实例(mdb=BeanDefinition) 【核心方法】instanceWrapper = this.createBeanInstance(beanName, mbd, args);}Object bean = instanceWrapper.getWrappedInstance();Class<?> beanType = instanceWrapper.getWrappedClass();if (beanType != NullBean.class) {mbd.resolvedTargetType = beanType;}synchronized(mbd.postProcessingLock) {if (!mbd.postProcessed) {try {this.applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);} catch (Throwable var17) {// 抛出异常 }mbd.markAsPostProcessed();}}boolean earlySingletonExposure = mbd.isSingleton() && this.allowCircularReferences && this.isSingletonCurrentlyInCreation(beanName);if (earlySingletonExposure) {// 打印日志 }this.addSingletonFactory(beanName, () -> {return this.getEarlyBeanReference(beanName, mbd, bean);});}Object exposedObject = bean;try {// 填充bean属性; this.populateBean(beanName, mbd, instanceWrapper);// 初始化bean exposedObject = this.initializeBean(beanName, exposedObject, mbd);} catch (Throwable var18) {// 抛出异常 }// ...try {// 注册可销毁bean this.registerDisposableBeanIfNecessary(beanName, bean, mbd);return exposedObject;} catch (BeanDefinitionValidationException var16) {// 抛出异常 }}
9)调用AbstractAutowireCapableBeanFactory#createBeanInstance()创建bean实例
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {Class<?> beanClass = this.resolveBeanClass(mbd, beanName, new Class[0]);if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {// 抛出异常 } else {if (args == null) {Supplier<?> instanceSupplier = mbd.getInstanceSupplier();if (instanceSupplier != null) {return this.obtainFromSupplier(instanceSupplier, beanName, mbd);}}if (mbd.getFactoryMethodName() != null) { // 如果是工厂方法名,即如果bean时工厂方法bean,则使用工厂方法实例化bean return this.instantiateUsingFactoryMethod(beanName, mbd, args);} else {boolean resolved = false;boolean autowireNecessary = false;if (args == null) {synchronized(mbd.constructorArgumentLock) {if (mbd.resolvedConstructorOrFactoryMethod != null) {resolved = true;autowireNecessary = mbd.constructorArgumentsResolved;}}}if (resolved) {return autowireNecessary ? this.autowireConstructor(beanName, mbd, (Constructor[])null, (Object[])null) : this.instantiateBean(beanName, mbd);} else {// 进入这个分支 // 从Bean后置处理器决定构造器 Constructor<?>[] ctors = this.determineConstructorsFromBeanPostProcessors(beanClass, beanName);if (ctors == null && mbd.getResolvedAutowireMode() != 3 && !mbd.hasConstructorArgumentValues() && ObjectUtils.isEmpty(args)) {// 获取首选构造器为null,则使用this.instantiateBean(beanName, mbd)实例化bean ctors = mbd.getPreferredConstructors();return ctors != null ? this.autowireConstructor(beanName, mbd, ctors, (Object[])null) : this.instantiateBean(beanName, mbd);} else {return this.autowireConstructor(beanName, mbd, ctors, args);}}}}}
10) 调用AbstractAutowireCapableBeanFactory#instantiateBean() 实例化bean
protected BeanWrapper instantiateBean(String beanName, RootBeanDefinition mbd) {try {// 获取实例化策略(CglibSubclassingInstantiationStrategy-cglib子类实例化策略) Object beanInstance = this.getInstantiationStrategy().instantiate(mbd, beanName, this);BeanWrapper bw = new BeanWrapperImpl(beanInstance);this.initBeanWrapper(bw);return bw;} catch (Throwable var5) {throw new BeanCreationException(mbd.getResourceDescription(), beanName, var5.getMessage(), var5);}}
11)调用 SimpleInstantiationStrategy#instantiate()实例化bean
public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {// 是否有方法重写 if (!bd.hasMethodOverrides()) { // 若没有方法重写Constructor constructorToUse;synchronized(bd.constructorArgumentLock) {constructorToUse = (Constructor)bd.resolvedConstructorOrFactoryMethod;if (constructorToUse == null) {Class<?> clazz = bd.getBeanClass();if (clazz.isInterface()) {throw new BeanInstantiationException(clazz, "Specified class is an interface");}try {// 获取构造器class constructorToUse = clazz.getDeclaredConstructor();bd.resolvedConstructorOrFactoryMethod = constructorToUse;} catch (Throwable var9) {throw new BeanInstantiationException(clazz, "No default constructor found", var9);}}}// 调用工具类根据构造器实例化class return BeanUtils.instantiateClass(constructorToUse, new Object[0]);} else {// 有方法重写,则使用方法注入实例化return this.instantiateWithMethodInjection(bd, beanName, owner);}
}
12)调用 BeanUtils.instantiateClass() 工具类方法 实例化bean ; 显然是通过反射实例化bean ;
public static <T> T instantiateClass(Constructor<T> ctor, Object... args) throws BeanInstantiationException {Assert.notNull(ctor, "Constructor must not be null");try {ReflectionUtils.makeAccessible(ctor);if (KotlinDetector.isKotlinReflectPresent() && KotlinDetector.isKotlinType(ctor.getDeclaringClass())) {return BeanUtils.KotlinDelegate.instantiateClass(ctor, args);} else {int parameterCount = ctor.getParameterCount();Assert.isTrue(args.length <= parameterCount, "Can't specify more arguments than constructor parameters");if (parameterCount == 0) {// 通过构造器clazz使用反射技术实例化bean【无参】return ctor.newInstance();} else {Class<?>[] parameterTypes = ctor.getParameterTypes();Object[] argsWithDefaultValues = new Object[args.length];for(int i = 0; i < args.length; ++i) {if (args[i] == null) {Class<?> parameterType = parameterTypes[i];argsWithDefaultValues[i] = parameterType.isPrimitive() ? DEFAULT_TYPE_VALUES.get(parameterType) : null;} else {argsWithDefaultValues[i] = args[i];}}// 通过构造器clazz使用反射技术实例化bean 【有参】 return ctor.newInstance(argsWithDefaultValues);}}} catch (//...) {// 抛出异常}
}
13)回到第10步,调用instantiateBean()方法;
接着调用 BeanWrapper bw = new BeanWrapperImpl(beanInstance);
protected BeanWrapper instantiateBean(String beanName, RootBeanDefinition mbd) {try {Object beanInstance = this.getInstantiationStrategy().instantiate(mbd, beanName, this);BeanWrapper bw = new BeanWrapperImpl(beanInstance);// 初始化Bean包裹器this.initBeanWrapper(bw); return bw;} catch (Throwable var5) {throw new BeanCreationException(mbd.getResourceDescription(), beanName, var5.getMessage(), var5);}}protected void initBeanWrapper(BeanWrapper bw) {bw.setConversionService(this.getConversionService());this.registerCustomEditors(bw); // 注册自定义编辑器}
AbstractBeanFactory.registerCustomEditors(bw); // 注册自定义编辑器
protected void registerCustomEditors(PropertyEditorRegistry registry) {if (registry instanceof PropertyEditorRegistrySupport registrySupport) {registrySupport.useConfigValueEditors();}if (!this.propertyEditorRegistrars.isEmpty()) {Iterator var9 = this.propertyEditorRegistrars.iterator();while(var9.hasNext()) {PropertyEditorRegistrar registrar = (PropertyEditorRegistrar)var9.next();try {registrar.registerCustomEditors(registry);} catch (BeanCreationException var8) {// 抛出异常...throw var8;}}}// 注册自定义属性编辑器 if (!this.customEditors.isEmpty()) {this.customEditors.forEach((requiredType, editorClass) -> {// 调用BeanUtils.instantiateClass() 通过反射实例化编辑器registry.registerCustomEditor(requiredType, (PropertyEditor)BeanUtils.instantiateClass(editorClass));});}}
14)回到第8步:AbstractAutowireCapableBeanFactory#doCreateBean(beanName, mbdToUse, args):使用BeanDefinition创建Bean
创建bean完成之后,调用populateBean() 填充bean属性,调用initializeBean()初始化bean ;
try {// 填充bean属性this.populateBean(beanName, mbd, instanceWrapper); // 初始化bean exposedObject = this.initializeBean(beanName, exposedObject, mbd); } catch (Throwable var18) {// 抛出异常 }
14.1)this.populateBean(beanName, mbd, instanceWrapper); // 填充bean属性
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {if (bw == null) {// 抛出异常} else if (bw.getWrappedClass().isRecord()) {// 抛出异常 } else {if (!mbd.isSynthetic() && this.hasInstantiationAwareBeanPostProcessors()) {Iterator var4 = this.getBeanPostProcessorCache().instantiationAware.iterator();while(var4.hasNext()) {InstantiationAwareBeanPostProcessor bp = (InstantiationAwareBeanPostProcessor)var4.next();if (!bp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {return;}}}PropertyValues pvs = mbd.hasPropertyValues() ? mbd.getPropertyValues() : null;int resolvedAutowireMode = mbd.getResolvedAutowireMode();if (resolvedAutowireMode == 1 || resolvedAutowireMode == 2) {MutablePropertyValues newPvs = new MutablePropertyValues((PropertyValues)pvs);if (resolvedAutowireMode == 1) {this.autowireByName(beanName, mbd, bw, newPvs);// 通过bean装配}if (resolvedAutowireMode == 2) {this.autowireByType(beanName, mbd, bw, newPvs);// 通过类型装配 }pvs = newPvs;}// 是否有实例化Aware装配后置处理器 if (this.hasInstantiationAwareBeanPostProcessors()) {if (pvs == null) {pvs = mbd.getPropertyValues();}PropertyValues pvsToUse;for(Iterator var11 = this.getBeanPostProcessorCache().instantiationAware.iterator(); var11.hasNext(); pvs = pvsToUse) {InstantiationAwareBeanPostProcessor bp = (InstantiationAwareBeanPostProcessor)var11.next();// 调用实例化装配后置处理器的后置处理属性方法-postProcessProperties() pvsToUse = bp.postProcessProperties((PropertyValues)pvs, bw.getWrappedInstance(), beanName); if (pvsToUse == null) {return;}}}boolean needsDepCheck = mbd.getDependencyCheck() != 0;if (needsDepCheck) {PropertyDescriptor[] filteredPds = this.filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);this.checkDependencies(beanName, mbd, filteredPds, (PropertyValues)pvs);}if (pvs != null) {// 把pvs赋值给bean的对应属性值 this.applyPropertyValues(beanName, mbd, bw, (PropertyValues)pvs); }}
}
14.2)调用AbstractAutowireCapableBeanFactory#initializeBean()初始化bean 【bean初始化-重要 】
protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {// 1 调用Aware装配方法this.invokeAwareMethods(beanName, bean); Object wrappedBean = bean;if (mbd == null || !mbd.isSynthetic()) {// 2 调用BeanPostProcessor的初始化前置方法wrappedBean = this.applyBeanPostProcessorsBeforeInitialization(bean, beanName); } try { // 3 调用初始化方法this.invokeInitMethods(beanName, wrappedBean, mbd);} catch (Throwable var6) {// 抛出异常 }if (mbd == null || !mbd.isSynthetic()) {// 4 调用BeanPostProcessor的初始化后置方法wrappedBean = this.applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);}return wrappedBean;}
14.2.1)调用Aware方法-invokeAwareMethods(),装配属性 【bean初始化-重要-第1步调用Aware接口方法 】
private void invokeAwareMethods(String beanName, Object bean) {if (bean instanceof Aware) {if (bean instanceof BeanNameAware) {BeanNameAware beanNameAware = (BeanNameAware)bean;beanNameAware.setBeanName(beanName); // 装配bean name}if (bean instanceof BeanClassLoaderAware) {BeanClassLoaderAware beanClassLoaderAware = (BeanClassLoaderAware)bean;ClassLoader bcl = this.getBeanClassLoader();if (bcl != null) { // 装配类加载器 beanClassLoaderAware.setBeanClassLoader(bcl);}}if (bean instanceof BeanFactoryAware) {BeanFactoryAware beanFactoryAware = (BeanFactoryAware)bean;beanFactoryAware.setBeanFactory(this);// 装配BeanFactory}}}
14.2.2)调用BeanPostProcessor的初始化前置方法-applyBeanPostProcessorsBeforeInitialization() 【bean初始化-重要-第2步调用BeanPostProcessor初始化前置方法 】
【AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsBeforeInitialization()】
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName) throws BeansException {Object result = existingBean;Object current;for(Iterator var4 = this.getBeanPostProcessors().iterator(); var4.hasNext(); result = current) {BeanPostProcessor processor = (BeanPostProcessor)var4.next();current = processor.postProcessBeforeInitialization(result, beanName);if (current == null) {return result;}}return result;
}
14.2.3)调用初始化方法-AbstractAutowireCapableBeanFactory#invokeInitMethods()【bean初始化-重要-第3步调用初始化方法,包括InitializingBean#afterPropertiesSet方法,init初始化方法 】
protected void invokeInitMethods(String beanName, Object bean, @Nullable RootBeanDefinition mbd) throws Throwable {boolean isInitializingBean = bean instanceof InitializingBean;if (isInitializingBean && (mbd == null || !mbd.hasAnyExternallyManagedInitMethod("afterPropertiesSet"))) {if (this.logger.isTraceEnabled()) {this.logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");}// 调用实例化bean#InitializingBean的事后属性设置方法afterPropertiesSet() ((InitializingBean)bean).afterPropertiesSet();}if (mbd != null && bean.getClass() != NullBean.class) {String[] initMethodNames = mbd.getInitMethodNames();if (initMethodNames != null) {String[] var6 = initMethodNames;int var7 = initMethodNames.length;for(int var8 = 0; var8 < var7; ++var8) {String initMethodName = var6[var8];if (StringUtils.hasLength(initMethodName) && (!isInitializingBean || !"afterPropertiesSet".equals(initMethodName)) && !mbd.hasAnyExternallyManagedInitMethod(initMethodName)) {// 调用配置的init()方法this.invokeCustomInitMethod(beanName, bean, mbd, initMethodName);}}}}}
14.2.4)调用AbstractAutowireCapableBeanFactory#BeanPostProcessor的初始化后置方法-applyBeanPostProcessorsAfterInitialization()【bean初始化-重要-第4步调用BeanPostProcessor初始化后置方法 】
同14.2.2 ,源代码略过; 只不过方法是后置方法-postProcessAfterInitialization()
15)再次回到第8步:AbstractAutowireCapableBeanFactory.doCreateBean(beanName, mbdToUse, args):使用BeanDefinition创建Bean
经过实例化bean, 初始化bean之后,最后调用registerDisposableBeanIfNecessary方法注册可销毁Bean-DisposableBean;
【AbstractBeanFactory#registerDisposableBeanIfNecessary()】注册可销毁Bean
protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {if (!mbd.isPrototype() && this.requiresDestruction(bean, mbd)) {if (mbd.isSingleton()) {// 注册可销毁Beanthis.registerDisposableBean(beanName, new DisposableBeanAdapter(bean, beanName, mbd, this.getBeanPostProcessorCache().destructionAware));} else {Scope scope = (Scope)this.scopes.get(mbd.getScope());if (scope == null) {throw new IllegalStateException("No Scope registered for scope name '" + mbd.getScope() + "'");}scope.registerDestructionCallback(beanName, new DisposableBeanAdapter(bean, beanName, mbd, this.getBeanPostProcessorCache().destructionAware));}}} // 注册可销毁bean
// 【DefaultSingletonBeanRegistry#registerDisposableBean()】
public void registerDisposableBean(String beanName, DisposableBean bean) {synchronized(this.disposableBeans) {this.disposableBeans.put(beanName, bean);}}
至此第8步doCreateBean()-创建Bean执行完成 ;
16)回到第7步:AbstractAutowireCapableBeanFactory#createBean()方法,创建bean:
调用第8步doCreateBean()创建bean, doCreateBean()执行完成,则第7步也执行完成;
接着回到第5步:singletonObject = singletonFactory.getObject(); 通过单例工厂获取单例bean对象,singletonFactory是lambda表达式(第6步)。
接着调用 this.afterSingletonCreation(beanName) , this=DefaultSingletonBeanRegistry ;
【DefaultSingletonBeanRegistry 】afterSingletonCreation()是一个protected方法,子类可以重写
protected void afterSingletonCreation(String beanName) {if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.remove(beanName)) {throw new IllegalStateException("Singleton '" + beanName + "' isn't currently in creation");}}
17)再回到第5步:接着调用this.addSingleton(beanName, singletonObject), 把单例bean添加到单例bean对象容器;
【DefaultSingletonBeanRegistry】
protected void addSingleton(String beanName, Object singletonObject) {synchronized(this.singletonObjects) {this.singletonObjects.put(beanName, singletonObject);this.singletonFactories.remove(beanName); this.earlySingletonObjects.remove(beanName);this.registeredSingletons.add(beanName);}
}
【DefaultSingletonBeanRegistry定义】默认单例bean注册类
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {private static final int SUPPRESSED_EXCEPTIONS_LIMIT = 100;private final Map<String, Object> singletonObjects = new ConcurrentHashMap(256);private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap(16);private final Map<String, Object> earlySingletonObjects = new ConcurrentHashMap(16);private final Set<String> registeredSingletons = new LinkedHashSet(256);private final Set<String> singletonsCurrentlyInCreation = Collections.newSetFromMap(new ConcurrentHashMap(16));private final Set<String> inCreationCheckExclusions = Collections.newSetFromMap(new ConcurrentHashMap(16));@Nullableprivate Set<Exception> suppressedExceptions;private boolean singletonsCurrentlyInDestruction = false;private final Map<String, DisposableBean> disposableBeans = new LinkedHashMap();private final Map<String, Set<String>> containedBeanMap = new ConcurrentHashMap(16);private final Map<String, Set<String>> dependentBeanMap = new ConcurrentHashMap(64);private final Map<String, Set<String>> dependenciesForBeanMap = new ConcurrentHashMap(64);public DefaultSingletonBeanRegistry() {}//...
}
18)再回到第4步:调用AbstractBeanFactory#doGetBean()方法获取bean; 上述第5步到第17步介绍的是this.getSingleton(beanName, ObjectFactory)的执行过程; 接着执行this.getObjectForBeanInstance() 获取bean实例的对象;
if (mbd.isSingleton()) {sharedInstance = this.getSingleton(beanName, () -> {try {return this.createBean(beanName, mbd, args);} catch (BeansException var5) {this.destroySingleton(beanName);throw var5;}});// 判断是否为工厂bean beanInstance = this.getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
【AbstractBeanFactory#getObjectForBeanInstance()】
protected Object getObjectForBeanInstance(Object beanInstance, String name, String beanName, @Nullable RootBeanDefinition mbd) {if (BeanFactoryUtils.isFactoryDereference(name)) {if (beanInstance instanceof NullBean) {return beanInstance;} else if (!(beanInstance instanceof FactoryBean)) {throw new BeanIsNotAFactoryException(beanName, beanInstance.getClass());} else {if (mbd != null) {mbd.isFactoryBean = true;}return beanInstance;}} else if (beanInstance instanceof FactoryBean) {// 若是工厂bean,则获取工厂bean对应的目标对象 FactoryBean<?> factoryBean = (FactoryBean)beanInstance;Object object = null;if (mbd != null) {mbd.isFactoryBean = true;} else {object = this.getCachedObjectForFactoryBean(beanName);}if (object == null) {if (mbd == null && this.containsBeanDefinition(beanName)) {mbd = this.getMergedLocalBeanDefinition(beanName);}boolean synthetic = mbd != null && mbd.isSynthetic();object = this.getObjectFromFactoryBean(factoryBean, beanName, !synthetic);}return object;} else {return beanInstance;}
}
19)实例化bean(this.getBean(beanName))完成后,回到第3步;调用 beanFactory.preInstantiateSingletons(); 预先实例化单例bean; beanFactory类型=DefaultListableBeanFactory;
判断bean是否为SmartInitializingSingleton,若是则调用其afterSingletonsInstantiated()方法;
【DefaultListableBeanFactory】
public void preInstantiateSingletons() throws BeansException {List<String> beanNames = new ArrayList(this.beanDefinitionNames);Iterator var2 = beanNames.iterator();String beanName;while(var2.hasNext()) {beanName = (String)var2.next();RootBeanDefinition bd = this.getMergedLocalBeanDefinition(beanName);if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {if (this.isFactoryBean(beanName)) { // 是否工厂bean Object bean = this.getBean("&" + beanName);if (bean instanceof SmartFactoryBean) {SmartFactoryBean<?> smartFactoryBean = (SmartFactoryBean)bean;if (smartFactoryBean.isEagerInit()) {this.getBean(beanName);}}} else { // 尝试获取bean,若bean不存在,则实例化bean this.getBean(beanName); }}}var2 = beanNames.iterator();while(var2.hasNext()) {beanName = (String)var2.next();Object singletonInstance = this.getSingleton(beanName);// 是否SmartInitializingSingletonif (singletonInstance instanceof SmartInitializingSingleton smartSingleton) { StartupStep smartInitialize = this.getApplicationStartup().start("spring.beans.smart-initialize").tag("beanName", beanName);// 调用smartSingleton的回调方法afterSingletonsInstantiated()-实例化完成后置方法 smartSingleton.afterSingletonsInstantiated(); smartInitialize.end();}}
}
20) (或有)调用敏捷初始化单例接口的实例化完成后置方法- SmartInitializingSingleton#afterSingletonsInstantiated()
public interface SmartInitializingSingleton {void afterSingletonsInstantiated();
}
【小结】至此,bean实例化即初始化流程执行完成;
【4】容器刷新收尾工作
1) 第12步:第12步是容器属性收尾代码逻辑; 调用finishRefresh()方法,容器刷新的收尾工作,包括清空缓存,注册生命周期处理器并执行其onRefresh(),发布ContextRefreshedEvent事件;
【4.1】容器刷新收尾工作主要步骤总结:
1)容器刷新收尾工作主要步骤总结:
- 重置公共缓存;
- 清理资源缓存;
- 初始化生命周期处理器;
- 调用生命周期处理器的onRefresh方法;
- 发布ContextRefreshedEvent事件;
【4.2】容器刷新收尾工作详细步骤源码分析
【AbstractApplicationContext】
protected void finishRefresh() {// Reset common introspection caches in Spring's core infrastructure.// 重置公共缓存resetCommonCaches();// Clear context-level resource caches (such as ASM metadata from scanning).// 清理资源缓存clearResourceCaches();// Initialize lifecycle processor for this context.initLifecycleProcessor();// Propagate refresh to lifecycle processor first.getLifecycleProcessor().onRefresh();// Publish the final event.publishEvent(new ContextRefreshedEvent(this));
}
1)调用resetCommonCaches()-重置公共缓存
protected void resetCommonCaches() {ReflectionUtils.clearCache();AnnotationUtils.clearCache();ResolvableType.clearCache();CachedIntrospectionResults.clearClassLoader(getClassLoader());
}
2)调用clearResourceCaches()清理资源缓存;
public void clearResourceCaches() {this.resourceCaches.clear();
}
3)调用initLifecycleProcessor() 初始化生命周期处理器;
protected void initLifecycleProcessor() {ConfigurableListableBeanFactory beanFactory = getBeanFactory();if (beanFactory.containsLocalBean(LIFECYCLE_PROCESSOR_BEAN_NAME)) {this.lifecycleProcessor = beanFactory.getBean(LIFECYCLE_PROCESSOR_BEAN_NAME, LifecycleProcessor.class);if (logger.isTraceEnabled()) {logger.trace("Using LifecycleProcessor [" + this.lifecycleProcessor + "]");}}else {// 注册默认生命周期处理器-DefaultLifecycleProcessor DefaultLifecycleProcessor defaultProcessor = new DefaultLifecycleProcessor();defaultProcessor.setBeanFactory(beanFactory);this.lifecycleProcessor = defaultProcessor;beanFactory.registerSingleton(LIFECYCLE_PROCESSOR_BEAN_NAME, this.lifecycleProcessor);// 日志}
}
4)调用getLifecycleProcessor().onRefresh();执行生命周期处理器的onRefresh方法;
public interface LifecycleProcessor extends Lifecycle {/*** Notification of context refresh, e.g. for auto-starting components.*/void onRefresh();/*** Notification of context close phase, e.g. for auto-stopping components.*/void onClose();}
5)调用publishEvent(new ContextRefreshedEvent(this)); 发布ContextRefreshedEvent事件;