Spring容器的AbstractApplicationContext#refresh()
【容器刷新】源码解析;本文只记录大体步骤, 细节部分自行阅读源码;
AbstractApplicationContext#refresh()
是IOC容器加载的主要流程,源代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 @Override public void refresh () throws BeansException, IllegalStateException { synchronized (this .startupShutdownMonitor) { prepareRefresh(); ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); prepareBeanFactory(beanFactory); try { postProcessBeanFactory(beanFactory); invokeBeanFactoryPostProcessors(beanFactory); registerBeanPostProcessors(beanFactory); initMessageSource(); initApplicationEventMulticaster(); onRefresh(); registerListeners(); finishBeanFactoryInitialization(beanFactory); finishRefresh(); } catch (BeansException ex) { if (logger.isWarnEnabled()) { logger.warn("Exception encountered during context initialization - " + "cancelling refresh attempt: " + ex); } destroyBeans(); cancelRefresh(ex); throw ex; } finally { resetCommonCaches(); } } }
逐步剖析 prepareRefresh(); 刷新前的预处理,在这里主要完成对Spring的启动时间进行记录、对系统变量的属性合法性进行校验、初始化容器事件列表
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 protected void prepareRefresh () { 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()); } } 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 <>(); }
obtainFreshBeanFactory(); 初始化BeanFactory;这一步主要完成了BeanFactory的创建以及获取;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 protected ConfigurableListableBeanFactory obtainFreshBeanFactory () { refreshBeanFactory(); return getBeanFactory(); } @Override 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); } } protected DefaultListableBeanFactory createBeanFactory () { return new DefaultListableBeanFactory (getInternalParentBeanFactory()); }
在源码中可以获得以下三个重要信息:
调用refreshBeanFactory()
方法创建了BeanFactory,它的默认实现是DefaultListableBeanFactory()
调用了loadBeanDefinitions()
方法,完成了配置文件的解析,并封装成了BeanDefinitions
对象存储到BeanFactory
中;
getBeanFactory();
获取创建好的BeanFactory
并返回
prepareBeanFactory(beanFactory); BeanFactory的预准备工作,对BeanFactory进行一些默认设置;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 protected void prepareBeanFactory (ConfigurableListableBeanFactory beanFactory) { beanFactory.setBeanClassLoader(getClassLoader()); beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver (beanFactory.getBeanClassLoader())); beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar (this , getEnvironment())); 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.registerResolvableDependency(BeanFactory.class, beanFactory); beanFactory.registerResolvableDependency(ResourceLoader.class, this ); beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this ); beanFactory.registerResolvableDependency(ApplicationContext.class, this ); beanFactory.addBeanPostProcessor(new ApplicationListenerDetector (this )); if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) { beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor (beanFactory)); beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader (beanFactory.getBeanClassLoader())); } 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()); } }
BeanFactory的一些必要配置,不赘述。
postProcessBeanFactory(beanFactory); BeanFactory准备工作完成后进行的后置处理工作,Spring预留的切入点,子类通过重写这个方法,在BeanFactory创建并预准备完成后做进一步的操作。
invokeBeanFactoryPostProcessors(beanFactory); 执行BeanFactoryPostProcessor
,BeanFactoryPostProcessor
是BeanFactory
的后置处理器,执行时机是BeanFactory
标准初始化之后执行的,涉及接口:BeanFactoryPostProcessor
、BeanDefinitionRegistryPostProcessor
等。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 protected void invokeBeanFactoryPostProcessors (ConfigurableListableBeanFactory beanFactory) { PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors()); if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) { beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor (beanFactory)); beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader (beanFactory.getBeanClassLoader())); } }
这部分主要就是执行容器中BeanFactoryPostProcessor
的子类,对其子类注入BeanFactory
,拆分一下执行流程大概分为以下四步:
获取所有BeanDefinitionRegistryPostProcessor
按照优先级进行排序,并按照优先级顺序执行BeanDefinitionRegistryPostProcessor#postProcessBeanDefinitionRegistry(registry);
,优先级顺序按照:实现PriorityOrdered
、实现Ordered
接口、未实现优先级接口
获取所有BeanFactoryPostProcessor
按照优先级进行排序,并按照先后顺序执行BeanFactoryPostProcessor#postProcessBeanFactory(beanFactory);
,优先级顺序按照:实现PriorityOrdered
、实现Ordered
接口、未实现优先级接口
registerBeanPostProcessors(beanFactory); 注册BeanPostProcessor
,BeanPostProcessor
是Bean的后置处理器,用于拦截Bean 的创建过程,以下为内置的一些BeanPostProcessor
:
BeanPostProcessor DestructionAwareBeanPostProcessor InstantiationAwareBeanPostProcessor SmartInstantiationAwareBeanPostProcessor MergedBeanDefinitionPostProcessor
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 protected void registerBeanPostProcessors (ConfigurableListableBeanFactory beanFactory) { PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this ); } 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, beanProcessorTargetCount)); 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); } } sortPostProcessors(priorityOrderedPostProcessors, beanFactory); registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors); List<BeanPostProcessor> orderedPostProcessors = new ArrayList <>(); 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); List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList <>(); for (String ppName : nonOrderedPostProcessorNames) { BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class); nonOrderedPostProcessors.add(pp); if (pp instanceof MergedBeanDefinitionPostProcessor) { internalPostProcessors.add(pp); } } registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors); sortPostProcessors(internalPostProcessors, beanFactory); registerBeanPostProcessors(beanFactory, internalPostProcessors); beanFactory.addBeanPostProcessor(new ApplicationListenerDetector (applicationContext)); }
上边代码比较长,其实做的事并没有这么复杂,主要就是对容器中后置处理器的排序,然后遍历注册的过程:
获取所有BeanPostProcessor
,不同接口类型的BeanPostProcessor
,执行时机不同;【后置处理器都可以通过PriorityOrdered
、Ordered
指定优先级】
按照优先级进行排序,并按照先后顺序注册(beanFactory#addBeanPostProcessor(postProcessor);
),优先级顺序:实现PriorityOrdered
、实现Ordered
接口、未实现优先级接口
最后注册MergedBeanDefinitionPostProcessor
类型的后置处理器
最终注册负责扫描发现监听器子类的处理器ApplicationListenerDetector
,在Bean创建完成后,检查是不是ApplicationListener
类型,如果是就注册到容器中
initMessageSource(); 初始化MessageSource
组件(国际化、消息绑定、消息解析)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 protected void initMessageSource () { ConfigurableListableBeanFactory beanFactory = getBeanFactory(); if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) { this .messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class); if (this .parent != null && this .messageSource instanceof HierarchicalMessageSource) { HierarchicalMessageSource hms = (HierarchicalMessageSource) this .messageSource; if (hms.getParentMessageSource() == null ) { hms.setParentMessageSource(getInternalParentMessageSource()); } } if (logger.isTraceEnabled()) { logger.trace("Using MessageSource [" + this .messageSource + "]" ); } } else { 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 + "]" ); } } }
在这一步可以看出,如果我们需要使用国际化组件,只需要把MessageSource
注册到容器中,获取国际化配置文件时,可以注入MessageSource
组件进行使用:
尝试在BeanFactory中获取id为messageSource
且类型为MessageSource
的组件
如果有就拿过来直接赋值;如果没有就自己创建一个DelegatingMessageSource
;
initApplicationEventMulticaster(); 初始化事件派发器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 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); if (logger.isTraceEnabled()) { logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " + "[" + this .applicationEventMulticaster.getClass().getSimpleName() + "]" ); } } }
这一步和国际化组件的初始化流程类型,可以我们自身指定它的实现,如果不指定也没关系,因为Spring会有自身默认的实现
尝试在BeanFactory中获取id为applicationEventMulticaster
且类型为ApplicationEventMulticaster
的组件;如果有则直接赋值到applicationEventMulticaster
如果未找到applicationEventMulticaster
组件,则会自动创建一个SimpleApplicationEventMulticaster
的事件派发器,并将其添加到添加到容器中
onRefresh(); 容器初始化期间执行的操作,子类重写这个方法,在容器刷新的时候可以自定义逻辑;如创建Tomcat,Jetty等WEB服务器
registerListeners(); 将所有事件监听器注册到容器中,也就是注册实现了ApplicationListener
的Bean
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 protected void registerListeners () { for (ApplicationListener<?> listener : getApplicationListeners()) { getApplicationEventMulticaster().addApplicationListener(listener); } String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true , false ); for (String listenerBeanName : listenerBeanNames) { getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName); } Set<ApplicationEvent> earlyEventsToProcess = this .earlyApplicationEvents; this .earlyApplicationEvents = null ; if (earlyEventsToProcess != null ) { for (ApplicationEvent earlyEvent : earlyEventsToProcess) { getApplicationEventMulticaster().multicastEvent(earlyEvent); } } }
总结下来其实也就是以下三个步骤:
拿到容器中所有ApplicationListener
将每个事件监听器添加到事件派发器中
派发之前产生的事件
finishBeanFactoryInitialization(beanFactory); 初始化所有剩下的单实例Bean,其中调用的beanFactory.preInstantiateSingletons();
方法用于实现初始化其余单实例Bean的逻辑
获取容器中所有的Bean,依次进行初始化和创建对象RootBeanDefinition
依次获取Bean的定义信息
判断Bean:不是抽象的 && 是单实例的 && 不是懒加载的
判断是否是FactoryBean:是否是实现了FactoryBean接口。如果是则调用getObject();
获取对象;
如果不是FactoryBean,利用getBean(beanName);
创建对象
先获取缓存中保存的单实例Bean,如果能获取到说明之前已经创建过(所有创建的Bean都会被缓存起来)Map singletonObjects = new ConcurrentHashMap(256);
如果缓存中获取不到Bean,开始创建Bean流程
标记当前Bean已经被创建【markBeanAsCreated(beanName);
】
获取Bean定义信息【final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
】
【获取当前Bean依赖的其它Bean(String[] dependsOn = mbd.getDependsOn();
)。如果有,按照getBean()
方式,把依赖的Bean先创建出来】
启动单实例Bean创建流程(createBean(beanName, mbd, args);
)
resolveBeforeInstantiation(beanName, mbdToUse);
让BeanPostProcessor
先拦截返回代理对象;如果是InstantiationAwareBeanPostProcessor
类型,则执行postProcessBeforeInstantiation
方法,如果有返回值,再触发postProcessAfterInitialization
方法
如果前边的InstantiationAwareBeanPostProcessor
没有返回代理对象,则执行3,如果返回了代理对象则直接返回Bean
执行Object beanInstance = doCreateBean(beanName, mbdToUse, args);
创建Bean
【创建Bean实例】createBeanInstance(beanName, mbd, args);
,利用工厂方法或对象构造器创建Bean实例
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
,调用MergedBeanDefinitionPostProcessor#postProcessMergedBeanDefinition
方法
【Bean属性赋值】populateBean(beanName, mbd, instanceWrapper);
执行InstantiationAwareBeanPostProcessor
后置处理器的postProcessAfterInstantiation
方法
执行InstantiationAwareBeanPostProcessor
后置处理器的postProcessPropertyValues
方法
applyPropertyValues(beanName, mbd, bw, pvs);
应用Bean的属性值,为属性利用getset方法等进行赋值
【Bean初始化】initializeBean(beanName, exposedObject, mbd);
【执行Aware】invokeAwareMethods(beanName, bean);
执行xxxAwaer接口方法;如:BeanNameAware
、BeanClassLoaderAware
、BeanFactoryAware
【执行后置处理器初始化之前的方法】applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
,执行BeanPostProcessor#postProcessBeforeInitialization
方法
【执行Bean初始化方法】invokeInitMethods(beanName, wrappedBean, mbd);
判断是不是实现了InitializingBean
接口,如果是执行该接口规定的初始化方法
判断是不是自定义了初始化方法
【执行初后置处理器初始化之后方法】applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
,执行BeanPostProcessor#postProcessAfterInitialization
方法
【注册Bean销毁方法】registerDisposableBeanIfNecessary(beanName, bean, mbd);
将创建的Bean存入缓存:singletonObjects
,IOC就是Map,很多的Map保存了单实例Bean、环境信息等。。。
所有Bean都利用getBean()
创建完成之后,检查所有的Bean是否实现了SmartInitializingSingleton
接口,如果是就执行afterSingletonsInstantiated
方法
finishRefresh(); 完成BeanFactory的初始化创建工作,IOC容器创建完成
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 protected void finishRefresh () { clearResourceCaches(); initLifecycleProcessor(); getLifecycleProcessor().onRefresh(); publishEvent(new ContextRefreshedEvent (this )); LiveBeansView.registerApplicationContext(this ); }
这一步主要就是完成一些收尾工作:
初始化生命周期相关后置处理器;我们可以写一个LifecycleProcessor
的实现类,可以在BeanFactory
刷新完成和关闭的时候进行一次自定义操作。
拿到生命周期处理器(LifecycleProcessor
),回调容器刷新完成方法
发布容器刷新完成事件
总结
Spring容器启动时,会保存所有注册进来的Bean定义信息;xml、注解方式
Spring容器会在合适的时机创建这些注册好的Bean,使用这个Bean的时候,利用getBean()
创建Bean,创建完成以后保存在容器中;方法finishBeanFactoryInitialization(beanFactory);
统一创建剩下的单实例Bean;
后置处理器:每一个Bean注册完成后,都会使用各种后置处理器进行处理,来增强Bean的功能;AutowireAnnotationBeanPostProcessor
【处理自动注入】、AnnotationAwareAspectJProxyCreator
【AOP功能】、AsyncAnnotationBeanPostProcessor
【异步处理接口】
事件驱动模型:ApplicationListener
【事件监听】、ApplicationEventMulticaster【事件派发】