作为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);}

Spring-- ApplicationContext相关推荐

  1. 使用Arthas 获取Spring ApplicationContext还原问题现场

    背景 最近来了个实习僧小弟,安排他实现对目标网站 连通性检测的小功能,简单讲就是将下边的shell 脚本换成Java 代码来实现 1#!/bin/bash2URL="https://www. ...

  2. Spring: ApplicationContext cannot be resolved to a type

    Spring: ApplicationContext cannot be resolved to a type 创建spring的IOC对象时 ApplicationContext ctx = new ...

  3. 从源码看spring applicationContext在web容器中加载过程

    2019独角兽企业重金招聘Python工程师标准>>> 原文:http://blog.csdn.net/fuliangliang/archive/2006/12/22/1454382 ...

  4. Spring:applicationContext.xml的头文件信息

    文章目录 Spring介绍 1.内核 2.提供服务 3.特性 4.体系结构 xml头文件代码展示 Spring介绍 分层的JavaSE/EE,应用full-stack(全栈)轻量级开源框架. 1.内核 ...

  5. spring applicationContext.xml最全约束

    <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.sp ...

  6. Spring - Java/J2EE Application Framework 应用框架 第 3 章 Beans, BeanFactory和ApplicationContext

    第 3 章 Beans, BeanFactory和ApplicationContext 3.1. 简介 在Spring中,两个最基本最重要的包是 org.springframework.beans 和 ...

  7. Spring中,applicationContext.xml 配置文件在web.xml中的配置详解

    Spring中,applicationContext.xml 配置文件在web.xml中的配置详解 2016年10月04日 15:22:26 阅读数:7936 转自http://www.cnblogs ...

  8. Spring IoC容器:BeanFactory和ApplicationContext

    在教程前面介绍 Spring 框架时,已经提到过 Spring 的 IoC(控制反转)思想,本节来详细介绍一下 Spring 的 Ioc 容器. IoC 是指在程序开发中,实例的创建不再由调用者管理, ...

  9. 2.15 Spring Framework 5.x 之ApplicationContext附加功能

    1.15 附加功能ApplicationContext 正如章节介绍中所讨论的,该org.springframework.beans.factory 包提供了管理和操作bean的基本功能,包括以编程方 ...

  10. Spring核心技术(十四)——ApplicationContext的额外功能

    在前文的介绍中我们知道,org.springframework.beans.factory包提供了一些基本的功能来管理和控制Bean,甚至通过编程的方式来实现.org.springframework. ...

最新文章

  1. 数据结构与算法 / 分治算法
  2. 什么是 XDoclet?
  3. 从零开始学前端:字符串和数组的方法 --- 今天你学习了吗?(JS:Day10)
  4. 不同程序语言的注释和变量要求
  5. 零基础学python知乎-35岁了零基础自学Python可行吗?
  6. 赛车游戏代码大全html,赛车游戏代码
  7. HDU 1017 A Mathematical Curiosity 数学题
  8. 根据Excel生成建表语句sql——工具介绍
  9. 华北科技计算机组成原理,华北科技学院—《计算机组成原理》设计性实验报告.doc...
  10. python开发酷q插件gui_Python酷Q应用开发
  11. mysql创建视图语句_查询视图的sql语句(mysql创建视图sql语句)
  12. python 抽签程序_抽签程序源码
  13. 绘制计算机网络拓扑图,绘制网络拓扑图1.ppt
  14. SQLite3下载与安装
  15. 第一章 MapReduce概述
  16. 比较两组数据的差异用什么图更直观_第四节 单因素完全随机实验设计及数据处理...
  17. 弱分类器 强分类器(弱学习器 强学习器)
  18. Python初学者(零基础学习Python入门)书籍、视频、资料分享
  19. pacman 查询_pacman常用命令
  20. Android项目实践(二)——日记本APP

热门文章

  1. STL模板整理 set
  2. Magic Leap有新动态!成立由斯蒂芬森领头的内容团队
  3. Android Navigation Drawer样式抽屉的使用
  4. 本地Git关联远程Git时遇到的一些问题
  5. Linux环境下Android开发环境的搭建
  6. jsp页面textarea中换行替换问题
  7. 迷你图标集大集合:5000+ 30套免费的图标
  8. 专家系列教程:遭受***后的证据有哪些?
  9. linux cal 命令详解
  10. JDK5--Annotation学习:基础(一)