AbstractApplicationContext
是 ApplicationContext
的一个抽象实现类。和普通的 BeanFactory
不同的是,ApplicationContext
可以检测到它的内部 BeanFactory
中定义的特殊 Bean:自动完成 BeanFactoryPostProcessor
、BeanPostProcessor
、ApplicationListener
的注册。
按照惯例,先来看下 AbstractApplicationContext
的继承结构,嗯,你会发现挺复杂的
不过不要紧,我们只关心它的 refresh
方法实现。refresh
方法来自 ConfigurableApplicationContext
接口,关于它的功能描述如下:
加载或刷新配置的持久化,这些配置可以来自 XML 文件、properties 文件、关心数据库等等。因为该方法是一个启动方法,如果失败了,它应该销毁已经创建的单例,以避免出现悬挂资源(dangling resources),换句话说,要么实例化所有的单例,要么一个也不实例化。
refresh 代码跟踪 接下来看下 refresh 方法的实现。
prepareRefresh 这里是做一些准备工作,包括设置开始时间、active 状态、PropertySources 的初始化等等
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 protected void prepareRefresh () { this .startupDate = System.currentTimeMillis(); this .closed.set(false ); this .active.set(true ); initPropertySources(); getEnvironment().validateRequiredProperties(); this .earlyApplicationEvents = new LinkedHashSet<>(); }
obtainFreshBeanFactory 告诉子类刷新内部的 BeanFactory,然后返回刷新后的 BeanFactory
1 2 refreshBeanFactory(); return getBeanFactory();
GenericApplicationContext
中的 refreshBeanFactory
实现如下:
1 2 3 4 5 6 7 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()); }
它只是设置下 SerializationId,实际的 beanFactory 初始化是在创建时完成的
1 2 3 public GenericApplicationContext () { this .beanFactory = new DefaultListableBeanFactory(); }
当然 refreshBeanFactory
也可以有其他的实现方式。
getBeanFactory
比较简单,就是返回已创建的 beanFactory
prepareBeanFactory 配置 BeanFactory 的标准 context 特征,例如设置 context 的 class loader 和 post processor
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()); } }
postProcessBeanFactory 对 BeanFactory 进行后处理,默认的实现为空,交给子类去扩展。可以对 beanFactory 进行想要的操作。比如 GenericWebApplicationContext
的实现如下:
1 2 3 4 5 6 7 8 protected void postProcessBeanFactory (ConfigurableListableBeanFactory beanFactory) { if (this .servletContext != null ) { beanFactory.addBeanPostProcessor(new ServletContextAwareProcessor(this .servletContext)); beanFactory.ignoreDependencyInterface(ServletContextAware.class); } WebApplicationContextUtils.registerWebApplicationScopes(beanFactory, this .servletContext); WebApplicationContextUtils.registerEnvironmentBeans(beanFactory, this .servletContext); }
invokeBeanFactoryPostProcessors 调用 BeanFactoryPostProcessor
1 2 3 4 5 6 7 8 9 10 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())); } }
首先通过 getBeanFactoryPostProcessors
方法取出已经注册到 BeanFactory 中的所有BeanFactoryPostProcessor
,然后交给 invokeBeanFactoryPostProcessors
方法去处理
处理流程 主要分为两个阶段:首先处理 BeanDefinitionRegistryPostProcessor
接口的回调,然后处理 BeanFactoryPostProcessor
接口的回调
BeanDefinitionRegistryPostProcessor 接口回调 这是第一个阶段,处理实现了 BeanDefinitionRegistryPostProcessor
接口的 bean 的回调。
判断 beanFactory 是否为 BeanDefinitionRegistry
类型的实例
是 BeanDefinitionRegistry 类型的实例 首先处理方法入参中传入的 beanFactoryPostProcessors,分别调用其 postProcessBeanDefinitionRegistry
方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) { if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) { BeanDefinitionRegistryPostProcessor registryProcessor = (BeanDefinitionRegistryPostProcessor) postProcessor; registryProcessor.postProcessBeanDefinitionRegistry(registry); registryProcessors.add(registryProcessor); } else { regularPostProcessors.add(postProcessor); } }
然后从 beanFactory 中获取所有实现了 BeanDefinitionRegistryPostProcessor
接口和 PriorityOrdered
接口的 bean,分别调用其 postProcessBeanDefinitionRegistry
方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 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); invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry); currentRegistryProcessors.clear();
接着是 beanFactory 中实现了 BeanDefinitionRegistryPostProcessor
接口和 Ordered
接口的 bean,分别调用其 postProcessBeanDefinitionRegistry
方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 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); invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry); currentRegistryProcessors.clear();
最后是其他实现了 BeanDefinitionRegistryPostProcessor
接口且还未处理过的 bean,分别调用其 postProcessBeanDefinitionRegistry
方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 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); invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry); currentRegistryProcessors.clear(); }
因为 BeanDefinitionRegistryPostProcessor
接口 继承自 BeanFactoryPostProcessor
接口,所以还需要回调 BeanFactoryPostProcessor
接口的 postProcessBeanFactory
方法
1 2 invokeBeanFactoryPostProcessors(registryProcessors, beanFactory); invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
不是 BeanDefinitionRegistry 类型的实例 这个就比较简单了,直接调用 BeanFactoryPostProcessor
的 postProcessBeanFactory
方法
1 2 3 for (BeanFactoryPostProcessor postProcessor : postProcessors) { postProcessor.postProcessBeanFactory(beanFactory); }
BeanFactoryPostProcessor 接口回调 这里说的 BeanFactoryPostProcessor 不包括接口入参的 beanFactoryPostProcessors,因为在上一步已经处理过了。也不包括 beanFactory 中实现了 BeanDefinitionRegistryPostProcessor
接口的 bean,这种情况也在上一步处理过了。
首先还是要从 beanFactory 中取出所有实现了 BeanFactoryPostProcessor 接口的 beanName
1 2 3 String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true , false );
按照是否实现了 PriorityOrdered
、Ordered
接口分为 3 类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>(); List<String> orderedPostProcessorNames = new ArrayList<>(); List<String> nonOrderedPostProcessorNames = new ArrayList<>(); for (String ppName : postProcessorNames) { if (processedBeans.contains(ppName)) { } 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); } }
先回调实现了 PriorityOrdered
接口的
1 2 sortPostProcessors(priorityOrderedPostProcessors, beanFactory); invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
接着是回调实现了 Ordered
接口的
1 2 3 4 5 6 List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(); for (String postProcessorName : orderedPostProcessorNames) { orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class)); } sortPostProcessors(orderedPostProcessors, beanFactory); invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
最后是未实现优先级接口的
1 2 3 4 5 List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(); for (String postProcessorName : nonOrderedPostProcessorNames) { nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class)); } invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
registerBeanPostProcessors 实例化并且调用所有已注册的 BeanPostProcessor
获取所有实现了 BeanPostProcessor 接口的 beanName
1 String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true , false );
按照是否实现了 PriorityOrdered
、Ordered
接口分为 3 类,实现了 MergedBeanDefinitionPostProcessor
接口单独拎出来,用于特殊处理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 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
接口的
1 2 sortPostProcessors(priorityOrderedPostProcessors, beanFactory); registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
再注册实现了 Ordered
接口的
1 2 3 4 5 6 7 8 9 10 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);
最后注册所有实现了 MergedBeanDefinitionPostProcessor
接口的
1 2 sortPostProcessors(internalPostProcessors, beanFactory); registerBeanPostProcessors(beanFactory, internalPostProcessors);
initMessageSource 对 messageSource 进行初始化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 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()); } } } else { DelegatingMessageSource dms = new DelegatingMessageSource(); dms.setParentMessageSource(getInternalParentMessageSource()); this .messageSource = dms; beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this .messageSource); }
initApplicationEventMulticaster 初始化上下文中的事件机制
1 2 3 4 5 6 7 8 9 10 11 12 13 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); } else { this .applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory); beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this .applicationEventMulticaster); } }
onRefresh 留给子类去实现,用于初始化其他特殊的 bean。比如 Spring Boot 中,ServletWebServerApplicationContext
就是在这一步去创建的 web server
1 2 3 4 5 6 7 8 9 protected void onRefresh () { super .onRefresh(); try { createWebServer(); } catch (Throwable ex) { throw new ApplicationContextException("Unable to start web server" , ex); } }
ServletWebServerApplicationContext
创建 web server
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 private void createWebServer () { WebServer webServer = this .webServer; ServletContext servletContext = getServletContext(); if (webServer == null && servletContext == null ) { ServletWebServerFactory factory = getWebServerFactory(); this .webServer = factory.getWebServer(getSelfInitializer()); } else if (servletContext != null ) { try { getSelfInitializer().onStartup(servletContext); } catch (ServletException ex) { throw new ApplicationContextException("Cannot initialize servlet context" , ex); } } initPropertySources(); }
registerListeners 检查 listener bean 并向容器注册
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 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); } }
finishBeanFactoryInitialization 完成当前 context 的 beanFactory 的初始化,初始化剩下所有的 singleton bean
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 if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) && beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) { beanFactory.setConversionService( beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)); } if (!beanFactory.hasEmbeddedValueResolver()) { beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal)); } String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false , false ); for (String weaverAwareName : weaverAwareNames) { getBean(weaverAwareName); } beanFactory.setTempClassLoader(null ); beanFactory.freezeConfiguration(); beanFactory.preInstantiateSingletons();
finishRefresh 完成当前 context 的 refresh
操作,调用 LifecycleProcessor
的 onRefresh
方法,发布 ContextRefreshedEvent
事件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 clearResourceCaches(); initLifecycleProcessor(); getLifecycleProcessor().onRefresh(); publishEvent(new ContextRefreshedEvent(this )); LiveBeansView.registerApplicationContext(this );
整体流程 整体流程如下图所示: