javascript
Spring-- ApplicationContext
作為Spring提供的較之BeanFactory 更為先進的IoC容器實現, ApplicationContext 除了擁有BeanFactory 支持的所有功能之外,還進一步擴展了基本容器的功能,包括 BeanFactoryPostProcessor 、 BeanPostProcessor 以及其他特殊類型bean的自動識別、容器啟動后bean實例的自動初始化、國際化的信息支持、容器內事件發布等。
繼承結構
?
ApplicationContext
從 ApplicationContext 的繼承機構可以看到, ApplicationContext 繼承了BeanFactory,也就是說,ApplicationContext 擁有BeanFactory的全部功能,ApplicationContext 是通過將容器的功能委派給DefaultListableBeanFactory來實現。除了繼承BeanFactory,還有ResourceLoader、EnvironmentCapable、ApplicationEventPublisher、MessageSource等接口,也就說明ApplicationContext 除了容器的功能外,還囊括了資源的處理、環境、事件發布、國際化等。
public interface ApplicationContext extends EnvironmentCapable, ListableBeanFactory, HierarchicalBeanFactory,MessageSource, ApplicationEventPublisher, ResourcePatternResolver {@NullableString getId();String getApplicationName();String getDisplayName();long getStartupDate();@NullableApplicationContext getParent();AutowireCapableBeanFactory getAutowireCapableBeanFactory() throws IllegalStateException; }ConfigurableApplicationContext
ConfigurableApplicationContext擴展了ApplicationContext的配置能力,以及增加了聲明周期管理以及關閉能力。
public interface ConfigurableApplicationContext extends ApplicationContext, Lifecycle, Closeable {String CONFIG_LOCATION_DELIMITERS = ",; \t\n";String CONVERSION_SERVICE_BEAN_NAME = "conversionService";String LOAD_TIME_WEAVER_BEAN_NAME = "loadTimeWeaver";String ENVIRONMENT_BEAN_NAME = "environment";String SYSTEM_PROPERTIES_BEAN_NAME = "systemProperties";String SYSTEM_ENVIRONMENT_BEAN_NAME = "systemEnvironment";String SHUTDOWN_HOOK_THREAD_NAME = "SpringContextShutdownHook";void setId(String id);void setParent(@Nullable ApplicationContext parent);void setEnvironment(ConfigurableEnvironment environment);@OverrideConfigurableEnvironment getEnvironment();void addBeanFactoryPostProcessor(BeanFactoryPostProcessor postProcessor);void addApplicationListener(ApplicationListener<?> listener);void addProtocolResolver(ProtocolResolver resolver);void refresh() throws BeansException, IllegalStateException;void registerShutdownHook();@Overridevoid close();boolean isActive();ConfigurableListableBeanFactory getBeanFactory() throws IllegalStateException; }?WebApplicationContext
WebApplicationContext擴展了ApplicationContext的Web應用能力。
public interface WebApplicationContext extends ApplicationContext {String ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE = WebApplicationContext.class.getName() + ".ROOT";String SCOPE_REQUEST = "request";String SCOPE_SESSION = "session";String SCOPE_APPLICATION = "application";/*** Name of the ServletContext environment bean in the factory.* @see javax.servlet.ServletContext*/String SERVLET_CONTEXT_BEAN_NAME = "servletContext";/*** Name of the ServletContext init-params environment bean in the factory.* <p>Note: Possibly merged with ServletConfig parameters.* ServletConfig parameters override ServletContext parameters of the same name.* @see javax.servlet.ServletContext#getInitParameterNames()* @see javax.servlet.ServletContext#getInitParameter(String)* @see javax.servlet.ServletConfig#getInitParameterNames()* @see javax.servlet.ServletConfig#getInitParameter(String)*/String CONTEXT_PARAMETERS_BEAN_NAME = "contextParameters";/*** Name of the ServletContext attributes environment bean in the factory.* @see javax.servlet.ServletContext#getAttributeNames()* @see javax.servlet.ServletContext#getAttribute(String)*/String CONTEXT_ATTRIBUTES_BEAN_NAME = "contextAttributes";@NullableServletContext getServletContext();}ConfigurableWebApplicationContext
ConfigurableWebApplicationContext綜合了ConfigurableApplicationContext的配置能力以及WebApplicationContext的Web應用能力。
public interface ConfigurableWebApplicationContext extends WebApplicationContext, ConfigurableApplicationContext {/*** Prefix for ApplicationContext ids that refer to context path and/or servlet name.*/String APPLICATION_CONTEXT_ID_PREFIX = WebApplicationContext.class.getName() + ":";/*** Name of the ServletConfig environment bean in the factory.* @see javax.servlet.ServletConfig*/String SERVLET_CONFIG_BEAN_NAME = "servletConfig";void setServletContext(@Nullable ServletContext servletContext);void setServletConfig(@Nullable ServletConfig servletConfig);@NullableServletConfig getServletConfig();void setNamespace(@Nullable String namespace);@NullableString getNamespace();void setConfigLocation(String configLocation);void setConfigLocations(String... configLocations);@NullableString[] getConfigLocations();}AbstractApplicationContext
AbstractApplicationContext為ApplicationContext抽象實現。實現了簡單的Context能力,定義了一些模板方法,需要由子類具體實現。
屬性
//MessageSource類在此應用上下文中實例的名字,如果沒有對應實例,消息解析功能會托管給其父應用上下文public static final String MESSAGE_SOURCE_BEAN_NAME = "messageSource";//LifecycleProcessor類在此應用上下文中實例的名字。如果沒有對應實例,將會默認使用DefaultLifecycleProcessorpublic static final String LIFECYCLE_PROCESSOR_BEAN_NAME = "lifecycleProcessor";//ApplicationEventMulticaster類在此應用中所對應的實例名字。如果沒有該實例,則默認使用SimpleApplicationEventMulticasterpublic static final String APPLICATION_EVENT_MULTICASTER_BEAN_NAME = "applicationEventMulticaster";static {//主動加載ContextClosedEvent 類信息,以避免在WebLogic8.1中,關閉應用是出現的ClassLoader問題ContextClosedEvent.class.getName();}protected final Log logger = LogFactory.getLog(getClass());private String id = ObjectUtils.identityToString(this);private String displayName = ObjectUtils.identityToString(this);@Nullableprivate ApplicationContext parent;@Nullableprivate ConfigurableEnvironment environment;private final List<BeanFactoryPostProcessor> beanFactoryPostProcessors = new ArrayList<>();/** 該應用啟動的時間點,時間戳,毫秒 */private long startupDate;/** 該應用是否處于激活狀態的標識 */private final AtomicBoolean active = new AtomicBoolean();/** 該應用是否已經關閉的標識 */private final AtomicBoolean closed = new AtomicBoolean();/** refresh和destroy兩個方法會synchronize在此對象上 */private final Object startupShutdownMonitor = new Object();/** 提供給JVM的鉤子方法,用以JVM在關閉時,同時關閉此應用上下文,清理資源 */@Nullableprivate Thread shutdownHook;/** 此應用上下文使用的資源解析器 */private ResourcePatternResolver resourcePatternResolver;/** 用以管理此應用上下文Bean生命周期的LifeProcessor */@Nullableprivate LifecycleProcessor lifecycleProcessor;/** 用于處理此應用上下文的MessageSource實例 */@Nullableprivate MessageSource messageSource;/** 用于事件發布的工具類 */@Nullableprivate ApplicationEventMulticaster applicationEventMulticaster;/** 預留的ApplicationListener */private final Set<ApplicationListener<?>> applicationListeners = new LinkedHashSet<>();/** 在refresh之前注冊的 ApplicationListener */@Nullableprivate Set<ApplicationListener<?>> earlyApplicationListeners;/** 已經發布過的應用上下文事件 */@Nullableprivate Set<ApplicationEvent> earlyApplicationEvents;ApplicationContext接口方法
protected void publishEvent(Object event, @Nullable ResolvableType eventType) {Assert.notNull(event, "Event must not be null");//把event裝飾城一個ApplicationEventApplicationEvent applicationEvent;if (event instanceof ApplicationEvent) {applicationEvent = (ApplicationEvent) event;}else {applicationEvent = new PayloadApplicationEvent<>(this, event);if (eventType == null) {eventType = ((PayloadApplicationEvent<?>) applicationEvent).getResolvableType();}}//multicaster如果初始化了,即廣播事件,否則加入earlyApplicationEvents,后續再處理if (this.earlyApplicationEvents != null) {this.earlyApplicationEvents.add(applicationEvent);}else {getApplicationEventMulticaster().multicastEvent(applicationEvent, eventType);}// Publish event 到父 contextif (this.parent != null) {if (this.parent instanceof AbstractApplicationContext) {((AbstractApplicationContext) this.parent).publishEvent(event, eventType);}else {this.parent.publishEvent(event);}}}?ConfigurableApplicationContext接口方法
//合并父context的Environment public void setParent(@Nullable ApplicationContext parent) {this.parent = parent;if (parent != null) {Environment parentEnvironment = parent.getEnvironment();if (parentEnvironment instanceof ConfigurableEnvironment) {getEnvironment().merge((ConfigurableEnvironment) parentEnvironment);}}}?
BeanFactory接口方法
都通過調用BeanFactory實現。getBeanFactory()方法由子類實現,返回內部 beanFactory。
ListableBeanFactory接口方法
都通過調用BeanFactory實現。getBeanFactory()方法由子類實現,返回內部 beanFactory。
HierarchicalBeanFactory接口方法
都通過調用BeanFactory實現。getBeanFactory()方法由子類實現,返回內部 beanFactory。
MessageSource接口方法
略
ResourcePatternResolver接口方法
略
?Lifecycle接口方法
聲明周期動作會觸發事件
public void start() {getLifecycleProcessor().start();publishEvent(new ContextStartedEvent(this));}@Overridepublic void stop() {getLifecycleProcessor().stop();publishEvent(new ContextStoppedEvent(this));}子類必須實現的方法
/**子類必須實現,實現實際配置加載能力。在其他初始化工作之前由refresh方法調用。*/protected abstract void refreshBeanFactory() throws BeansException, IllegalStateException;/** 子類必須實現,釋放內部bean factory。*/protected abstract void closeBeanFactory();/**子類必須返回內部beanFactory,必須實現lookup能力。子類在返回bean factory前必須檢查context是否active。* context關閉,則factory不可用。* @see #refreshBeanFactory()* @see #closeBeanFactory()*/@Overridepublic abstract ConfigurableListableBeanFactory getBeanFactory() throws IllegalStateException;ConfigurableApplicationContext接口
refresh
refresh()方法:加載或刷新配置。
public void refresh() throws BeansException, IllegalStateException {synchronized (this.startupShutdownMonitor) {// 刷新準備prepareRefresh();// 通知子類刷新內部 bean Factory。 Tell the subclass to refresh the internal bean factory.ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();//BeanFactory 準備。prepareBeanFactory(beanFactory);try {// 允許在context子類中對BeanFactory進行post-processing。postProcessBeanFactory(beanFactory);// 調用在context中注冊為bean的工廠處理器(BeanFactoryPostProcessor)。invokeBeanFactoryPostProcessors(beanFactory);// 注冊攔截bean創建的BeanProcessor。registerBeanPostProcessors(beanFactory);// 為context初始化消息源。initMessageSource();// 為context初始化事件多播。initApplicationEventMulticaster();// 初始化子類context中的其他特殊bean。onRefresh();// 檢查listener類型的bean并注冊它們。registerListeners();/ 實例化所有剩余的(non-lazy-init)單例。finishBeanFactoryInitialization(beanFactory);// 最后一步:發布相應的事件。finishRefresh();}catch (BeansException ex) {if (logger.isWarnEnabled()) {logger.warn("Exception encountered during context initialization - " +"cancelling refresh attempt: " + ex);}// Destroy already created singletons to avoid dangling resources.destroyBeans();// Reset 'active' flag.cancelRefresh(ex);// Propagate exception to caller.throw ex;}finally {// Reset common introspection caches in Spring's core, since we// might not ever need metadata for singleton beans anymore...resetCommonCaches();}}}prepareRefresh
刷新前的準備,對容器屬性的初始化,校驗屬性文件的合法性,保留早期事件
protected void prepareRefresh() {// Switch to active.this.startupDate = System.currentTimeMillis();this.closed.set(false);this.active.set(true);if (logger.isDebugEnabled()) {if (logger.isTraceEnabled()) {logger.trace("Refreshing " + this);}else {logger.debug("Refreshing " + getDisplayName());}}// 初始化屬性,留給子類initPropertySources();// 校驗屬性文件是否合法getEnvironment().validateRequiredProperties();// 保留早期事件if (this.earlyApplicationListeners == null) {this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);}else {// Reset local application listeners to pre-refresh state.this.applicationListeners.clear();this.applicationListeners.addAll(this.earlyApplicationListeners);}// 清空,保證當multicaster可用時,可以立即廣播事件。this.earlyApplicationEvents = new LinkedHashSet<>();}obtainFreshBeanFactory
// 通知子類刷新內部 bean Factory。 Tell the subclass to refresh the internal bean factory.
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() { //子類實現refreshBeanFactory();return getBeanFactory();}prepareBeanFactory
給beanFactory賦值一些屬性。
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {// Tell the internal bean factory to use the context's class loader etc.// 設置類加載器beanFactory.setBeanClassLoader(getClassLoader());// 設置表達式解析器beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));// 添加屬性編輯器beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));// 添加ApplicationContextAwareProcessor,根據不同的類型加入不同的屬性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 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.// 注冊ApplicationListenerDetector,如果bean是ApplicationListener的,加入到事件派發器beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));// Detect a LoadTimeWeaver and prepare for weaving, if found.// 增加對AspectJ的支持if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));// Set a temporary ClassLoader for type matching.beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));}// Register default environment beans.// 注冊默認的環境beanif (!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());}}invokeBeanFactoryPostProcessors?
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 (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));}}protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);}上面2個函數都調用了類PostProcessorRegistrationDelegate的靜態方法。
PostProcessorRegistrationDelegate是AbstractApplicationContext委托執行post processors任務的工具類
這里的postProcessor包括兩類 :
- BeanFactoryPostProcessor
- BeanPostProcessor
實際上BeanFactoryPostProcessor又細分為兩類:
- BeanDefinitionRegistryPostProcessor:BeanDefinitionRegistry后置處理器
- BeanFactoryPostProcessor:BeanFactory后置處理器
BeanDefinitionRegistryPostProcessor其實繼承自BeanFactoryPostProcessor,是一種特殊的BeanFactoryPostProcessor。
BeanDefinitionRegistryPostProcessor的設計目的是在常規BeanFactoryPostProcessor處理BeanFactory(也就是容器)前先對bean注冊做處理,比如注冊更多的bean,實現方法為BeanDefinitionRegistryPostProcessor定義的postProcessBeanDefinitionRegistry。
如果一個實現類是BeanDefinitionRegistryPostProcessor,那么它的postProcessBeanDefinitionRegistry方法總是要早于它的postProcessBeanFactory方法被調用。
BeanFactoryPostProcessor 是針對?BeanFactory?的擴展,主要用在 bean?實例化之前,讀取 bean 的定義,并可以修改它。
BeanPostProcessor?是針對?bean?的擴展,主要用在 bean?實例化之后,執行初始化方法前后,允許開發者對?bean 實例進行修改。
invokeBeanFactoryPostProcessors
BeanFactoryPostProcessor 接口是 Spring 初始化?BeanFactory 時對外暴露的擴展點,Spring IoC 容器允許 BeanFactoryPostProcessor 在容器實例化任何?bean 之前讀取 bean 的定義,并可以修改它。
BeanDefinitionRegistryPostProcessor 繼承自 BeanFactoryPostProcessor,比 BeanFactoryPostProcessor 具有更高的優先級,主要用來在常規的 BeanFactoryPostProcessor 檢測開始之前注冊其他?bean 定義。特別是,你可以通過 BeanDefinitionRegistryPostProcessor 來注冊一些常規的 BeanFactoryPostProcessor,因為此時所有常規的 BeanFactoryPostProcessor 都還沒開始被處理。?
注:這邊的 “常規 BeanFactoryPostProcessor” 主要用來跟 BeanDefinitionRegistryPostProcessor 區分。
?
/*** 調用BeanFactoryPostProcessor* * @參數 beanFactory 應用上下文的 BeanFactory 實例* @參數 beanFactoryPostProcessors 應用上下文指定要執行的 BeanFactoryPostProcessor**/public static void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {//如果同時是BeanDefinitionRegistryPostProcessors類,則必須先調用postProcessBeanDefinitionRegistrySet<String> processedBeans = new HashSet<>();if (beanFactory instanceof BeanDefinitionRegistry) {BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;//普通BeanFactoryPostProcessorList<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();// 遍歷所有參數傳遞進來的 BeanFactoryPostProcessor(它們并沒有作為bean注冊在容器中)// 將所有參數傳入的 BeanFactoryPostProcessor 分成兩組 : // BeanDefinitionRegistryPostProcessor 和常規 BeanFactoryPostProcessor// 1.如果是BeanDefinitionRegistryPostProcessor,現在執行postProcessBeanDefinitionRegistry(),// 2.否則記錄為一個常規 BeanFactoryPostProcessor,現在不執行處理for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {BeanDefinitionRegistryPostProcessor registryProcessor =(BeanDefinitionRegistryPostProcessor) postProcessor;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.// currentRegistryProcessors 用于記錄當前正要被執行的BeanDefinitionRegistryPostProcessor//BeanDefinitionRegistryPostProcessors分為實現了:PriorityOrdered,注解了@Ordered 和其他。List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();//CODE:1.1// First, 實現了PriorityOrdered.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();//CODE:1.2// Next,注解了@Ordered.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();// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.//對 Bean形式BeanDefinitionRegistryPostProcessor, //并且未實現PriorityOrdered或者Ordered接口進行處理,直到沒有未被處理的boolean reiterate = true;while (reiterate) {reiterate = false;//CODE:1.3postProcessorNames = 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();}// Now, invoke the postProcessBeanFactory callback of all processors handled so far.// 因為BeanDefinitionRegistryPostProcessor繼承自BeanFactoryPostProcessor,所以這里// 也對所有 BeanDefinitionRegistryPostProcessor 調用其方法 postProcessBeanFactory() invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);}else {// Invoke factory processors registered with the context instance.invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);}// 以上邏輯執行了所有參數傳入的(參數:beanFactoryPostProcessors)和以bean定義方式存在的BeanDefinitionRegistryPostProcessor(見上面代碼:CODE:1.1,CODE:1.2,CODE:1.3),// 也執行了所有參數傳入的(參數:beanFactoryPostProcessors) BeanFactoryPostProcessor, 但是尚未處理所有以bean定義方式存在的// BeanFactoryPostProcessor, 下面的邏輯處理這部分 BeanFactoryPostProcessor.// 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.// 同BeanDefinitionRegistryPostProcessor, 將所有目前記錄的所有BeanFactoryPostProcessor分成三部分 :// 1. 實現了 PriorityOrdered 接口的,// 2. 實現了 Ordered 接口的,// 3. 其他.// 接下來的邏輯會對這三種BeanFactoryPostProcessor分別處理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);}}// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.sortPostProcessors(priorityOrderedPostProcessors, beanFactory);invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);// Next, invoke the BeanFactoryPostProcessors that implement Ordered.List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());for (String postProcessorName : orderedPostProcessorNames) {orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));}sortPostProcessors(orderedPostProcessors, 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));}invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);// Clear cached merged bean definitions since the post-processors might have// modified the original metadata, e.g. replacing placeholders in values...beanFactory.clearMetadataCache();}private static void invokeBeanFactoryPostProcessors(Collection<? extends BeanFactoryPostProcessor> postProcessors, ConfigurableListableBeanFactory beanFactory) {for (BeanFactoryPostProcessor postProcessor : postProcessors) {postProcessor.postProcessBeanFactory(beanFactory);}}registerBeanPostProcessors
本方法會注冊所有的 BeanPostProcessor,將所有實現了 BeanPostProcessor 接口的類加載到 BeanFactory 中。
BeanPostProcessor?接口是 Spring 初始化?bean 時對外暴露的擴展點,Spring IoC 容器允許?BeanPostProcessor?在容器初始化?bean?的前后,添加自己的邏輯處理。在 registerBeanPostProcessors 方法只是注冊到 BeanFactory 中,具體調用是在?bean 初始化的時候。
具體的:在所有?bean?實例化時,執行初始化方法前會調用所有?BeanPostProcessor?的 postProcessBeforeInitialization 方法,在執行初始化方法后會調用所有 BeanPostProcessor?的 postProcessAfterInitialization 方法。
public static void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {// 1、找到所有注冊到容器的 BeanPostProcessor 的名字String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);// Register BeanPostProcessorChecker that logs an info message when// a bean is created during BeanPostProcessor instantiation, i.e. when// a bean is not eligible for getting processed by all BeanPostProcessors./ BeanPostProcessor的目標計數,用于統計BeanPostProcessors 處理數量比較。int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;// 2、添加BeanPostProcessorChecker(主要用于記錄信息)到beanFactory中beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));// Separate between BeanPostProcessors that implement PriorityOrdered,// Ordered, and the rest.// 3.定義不同的變量用于區分: 實現PriorityOrdered接口的BeanPostProcessor、實現Ordered接口的BeanPostProcessor、普通BeanPostProcessorList<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);}}// First, register the BeanPostProcessors that implement PriorityOrdered.sortPostProcessors(priorityOrderedPostProcessors, beanFactory);registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);// Next, register the BeanPostProcessors that implement Ordered.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);// Now, register all regular BeanPostProcessors.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);// Finally, re-register all internal BeanPostProcessors.// 最后, 重新注冊所有內部BeanPostProcessors(相當于內部的BeanPostProcessor會被移到處理器鏈的末尾)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(跟8類似,主要是為了移動到處理器鏈的末尾)beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));}registerListeners
protected void registerListeners() {// Register statically specified listeners first.//首選注入應用級別listener 。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 (earlyEventsToProcess != null) {for (ApplicationEvent earlyEvent : earlyEventsToProcess) {getApplicationEventMulticaster().multicastEvent(earlyEvent);}}}finishBeanFactoryInitialization
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {// Initialize conversion service for this context.// 如果beanFactory存在conversionService,賦值給ConversionServiceif (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {beanFactory.setConversionService(beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));}// Register a default embedded value resolver if no bean post-processor// (such as a PropertyPlaceholderConfigurer bean) registered any before:// at this point, primarily for resolution in annotation attribute values.if (!beanFactory.hasEmbeddedValueResolver()) {beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));}// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.String[] weaverAwareNames = beanFactoryFactoryBean.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);for (String weaverAwareName : weaverAwareNames) {getBean(weaverAwareName);}// Stop using the temporary ClassLoader for type matching.// 此時不能用臨時加載器了beanFactory.setTempClassLoader(null);// Allow for caching all bean definition metadata, not expecting further changes.// 凍結所有bean的定義,此時不希望bean的定義被修改beanFactory.freezeConfiguration();// Instantiate all remaining (non-lazy-init) singletons.// 初始化剩下的單例,且除了延遲加載的beanbeanFactory.preInstantiateSingletons(); }finishRefresh
protected void finishRefresh() {// 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));// Participate in LiveBeansView MBean, if active.LiveBeansView.registerApplicationContext(this);}?
超強干貨來襲 云風專訪:近40年碼齡,通宵達旦的技術人生總結
以上是生活随笔為你收集整理的Spring-- ApplicationContext的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring WebApplicatio
- 下一篇: Spring BeanDefinitio