Spring源码之ApplicationContext

34次阅读

共计 34134 个字符,预计需要花费 86 分钟才能阅读完成。

​ 本文是针对 Srping 的 ClassPathXMLApplicationContext 来进行源码解析, 在本篇博客中将不会讲述 spring Xml 解析注册代码,因为 ApplicationContext 是 BeanFactory 的扩展版本 ApplicationContext 的 GetBean 和 xml 解析注册 BeanDefinition 都是用一套代码,如果您是第一次看请先看一下 XMLBeanFactory 解析和 BeanFactory.GetBean 源码解析:

  • XMLBeanFactory 源码解析地址:https://blog.csdn.net/qq_3025…
  • BeanFactory.getBean 源码解析地址:https://blog.csdn.net/qq_3025…

作者整理了 spring-framework 5.x 的源码注释,代码已经上传者作者的 GitHub 了,可以让读者更好的理解,地址:

  • GItHub:https://github.com/lantaoGitH…
  • 接下来我们你直接上源码:
package lantao;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.lantao.UserBean;

public class ApplicationContextTest {public static void main(String[] args) {ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-bean.xml");
        UserBean userBean = (UserBean) applicationContext.getBean("userBean");
        System.out.println(userBean.getName());
    }

}

在这里直接使用 ClassPathXmlApplicationContext 进行 xml 解析,在这里 xml 解析的代码和 GetBean 的代码就不过多的描述了,ApplicationContext 是 BeanFactory 的扩展,所以想要看这两部分源码的请看作者的上两篇博客 Sprin 源码解析;

  • 接下来我们看一下 ClassPathXmlApplicationContext 的源码:
/**
 * Create a new ClassPathXmlApplicationContext with the given parent,
 * loading the definitions from the given XML files.
 * @param configLocations array of resource locations
 * @param refresh whether to automatically refresh the context,
 * loading all bean definitions and creating all singletons.
 * Alternatively, call refresh manually after further configuring the context.
 * @param parent the parent context
 * @throws BeansException if context creation failed
 * @see #refresh()
 */
public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
        throws BeansException {super(parent);
    // 支持解析多文件
    setConfigLocations(configLocations);
    if (refresh) {refresh();
    }
}

在 setConfigLocations 方法中将资源文件放入 configLocations 全局变量中,,并且支持多文件解析,接下来我们你看一下重点,refresh 方法;

  • 源码 refresh 方法:
@Override
public void refresh() throws BeansException, IllegalStateException {synchronized (this.startupShutdownMonitor) {
        // Prepare this context for refreshing.
        // 准备刷新上下文
        prepareRefresh();

        // Tell the subclass to refresh the internal bean factory.
        // 对 beanFactory 的各种功能填充,加载 beanFactory,经过这个方法 applicationContext 就有了 BeanFactory 的所有功能
        ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

        // Prepare the bean factory for use in this context.
        // 对 beanFactory 进行各种功能填充
        prepareBeanFactory(beanFactory);

            try {
            // Allows post-processing of the bean factory in context subclasses.
            //  允许在 context 子类中对 BeanFactory 进行 post-processing。// 允许在上下文子类中对 Bean 工厂进行后处理
            // 可以在这里进行 硬编码形式的 BeanFactoryPostProcessor 调用 addBeanFactoryPostProcessor
            postProcessBeanFactory(beanFactory);

            // Invoke factory processors registered as beans in the context.
            // 激活各种 BeanFactory 处理器 BeanFactoryPostProcessors 是在实例化之前执行
            invokeBeanFactoryPostProcessors(beanFactory);

            // Register bean processors that intercept bean creation.
            // 注册 拦截 Bean 创建 的 Bean 处理器,这里只是注册,真正地调用在 getBean 的时候  BeanPostProcessors 实在 init 方法前后执行 doCreateBean 方法中的 实例化方法中执行
            // BeanPostProcessor 执行位置:doCreateBean --> initializeBean --> applyBeanPostProcessorsBeforeInitialization 和 applyBeanPostProcessorsAfterInitialization
            registerBeanPostProcessors(beanFactory);

            // Initialize message source for this context.
            // 为上下文初始化 Message 源,(比如国际化处理)这里没有过多深入
            initMessageSource();

            // Initialize event multicaster for this context.
            // 初始化应用消息广播,并放入 applicationEventMulticaster bean 中
            initApplicationEventMulticaster();

            // Initialize other special beans in specific context subclasses.
            // 留给子类来初始化其它的 bean
            onRefresh();

            // Check for listener beans and register them.
            // 在所有注册的 bean 中查找 Listener bean,注册到消息广播器中
            registerListeners();

            // Instantiate all remaining (non-lazy-init) singletons.
            // 初始化剩下的单实例
            finishBeanFactoryInitialization(beanFactory);

            // Last step: publish corresponding event.
            // 完成刷新过程,通知生命周期护处理器 lifecycleProcessor 刷新过程,同时发出 ContextRefreshEvent 通知别人(LifecycleProcessor 用来与所有声明的 bean 的周期做状态更新)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();}
    }
}

对于 ApplicationContext 来说,refresh 方法几乎涵盖了所有的基础和扩展功能,接下来看一下这个方法都做了什么;

  1. 刷新上下文,初始化前的准备工作;
  2. 加载 beanFactory,经过这个方法 applicationContext 就有了 BeanFactory 的所有功能
  3. 对 beanFactory 进行各种功能填充
  4. 允许在这里对 BeanFactory 的二次加工,例如:可以在这里进行硬编码方法的对 BeanFactory 进行 BeanFactoryPostProcessor 或 BeanPostProcessor 的操作;在这里简单说一下 BeanFactoryPostProcessor 是在 bean 实例化之前执行的,BeanPostProcessor 是在初始化方法前后执行的,BeanFactoryPostProcessor 操作的是 BeanFactoryBeanPostProcessor 操作的是 Bean,其次这里还涉及了一个扩展 BeanDefinitionRegistryPostProcessor 它是继承了 BeanFactoryPostProcessor,并且还有自己的定义方法 postProcessBeanDefinitionRegistry,这个方法可以操作 BeanDefinitionRegistry,BeanDefinitionRegistry 有个最主要的方法就是 registerBeanDefinition,可以注册 BeanDefinition,可以用这方法来处理一下不受 spring 管理的一下 bean;
  5. 处理所有的 BeanFactoryPostProcessor,也可以说是激活 BeanFactory 处理器,在这个方法里会先处理 BeanDefinitionRegistryPostProcessor,在处理 BeanFactoryPostProcessor,因为 BeanDefinitionRegistryPostProcessor 有自己的定义,所以先执行;
  6. 注册 BeanPostProcessors,这里只是注册,真正地调用在 getBean 的时候 BeanPostProcessors 实在 init 方法前后执行 BeanPostProcessor 执行位置:doCreateBean –> initializeBean –> applyBeanPostProcessorsBeforeInitialization 和 applyBeanPostProcessorsAfterInitialization 方法中;
  7. 为上下文初始化 Message 源,(比如国际化处理)这里没有过多深入;
  8. 初始化应用消息广播,初始化 applicationEventMulticaster,判断使用自定义的还是默认的;
  9. 留给子类来初始化其它的 bean;
  10. 在所有注册的 bean 中查找 ApplicationListener bean,注册到消息广播器中;
  11. 初始化剩下的单实例(非懒加载),这里会是涉及 conversionService,LoadTimeWeaverAware,冻结 BeanFactory,初始化 Bean 等操作;
  12. 完成刷新过程,包括 清除 下文级资源 (例如扫描的元数据),通知生命周期护处理器 lifecycleProcessor 并 strat,同时 publish Event 发出 ContextRefreshEvent 通知别人;
  • 先来看 prepareRefresh 方法:
/**
 * Prepare this context for refreshing, setting its startup date and
 * active flag as well as performing any initialization of property sources.
 */
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());
        }
    }

    // Initialize any placeholder property sources in the context environment.
    // 对上下文环境中的任何属性源进行分类。initPropertySources();

    // Validate that all properties marked as required are resolvable:
    // see ConfigurablePropertyResolver#setRequiredProperties,// 验证标示为必填的属性信息是否都有了 ConfigurablePropertyResolver#setRequiredProperties 方法
    getEnvironment().validateRequiredProperties();

    // Store pre-refresh ApplicationListeners...
    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);
    }

    // Allow for the collection of early ApplicationEvents,
    // to be published once the multicaster is available...
    this.earlyApplicationEvents = new LinkedHashSet<>();}

一眼望去,可能觉得这个方法没有做什么,其实这方法中除了 Closed 和 Active 最终要的是 initPropertySources 和 getEnvironment().validateRequiredProperties() 方法;

  1. initPropertySources 证符合 Spring 的开放式结构设计,给用户最大扩展 Spring 的能力。用户可以根据自身的需要重写 initPropertySourece 方法,并在方法中进行个性化的属性处理及设置。
  2. validateRequiredProperties 则是对属性进行验证,那么如何验证呢?举个融合两句代码的小例子来理解。

例如现在有这样一个需求,工程在运行过程中用到的某个设置(例如 VAR)是从系统环境变量中取得的,而如果用户没有在系统环境变量中配置这个参数,工程不会工作。这一要求也各种各样许有的解决办法,在 Spring 中可以这么做,可以直接修改 Spring 的源码,例如修改 ClassPathXmlApplicationContext. 淡然,最好的办法是对源码进行扩展,可以自定义类:

public class MyClassPathXmlApplicationContext extends ClassPathXmlApplicationContext{public MyClassPathXmlApplicationContext(String.. configLocations){super(configLocations);
       }
       protected void initPropertySources(){
             // 添加验证要求
             getEnvironment().setRequiredProterties("VAR");}
}

自定义了继承自 ClassPathXmlApplicationContext 的 MyClassPathXmlApplicationContext, 并重写了 initPropertySources 方法,在方法中添加了个性化需求,那么在验证的时候也就是程序走到 getEnvironment().validateRequiredProperties() 代码的时候,如果系统并没有检测到对应 VAR 的环境变量,将抛出异常。当然我们还需要在使用的时候替换掉原有的 ClassPathXmlApplicationContext:

public static void main(Stirng[] args){ApplicationContext bf = new MyClassPathXmlApplicationContext("myTest.xml");User user = (User)bf.getBean("testBean");
   }

上述案例来源于:Spring 源码深度解析(第二版)141 页;

  • 接下来看一下 obtainFreshBeanFactory 方法,在这里初始化 DefaultListAbleBeanFactory 并解析 xml:
/**
 * Tell the subclass to refresh the internal bean factory.
 * @return the fresh BeanFactory instance
 * @see #refreshBeanFactory()
 * @see #getBeanFactory()
 */
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {refreshBeanFactory();
    return getBeanFactory();}

/**
 * This implementation performs an actual refresh of this context's underlying
 * bean factory, shutting down the previous bean factory (if any) and
 * initializing a fresh bean factory for the next phase of the context's lifecycle.
 */
@Override
protected final void refreshBeanFactory() throws BeansException {if (hasBeanFactory()) {destroyBeans();
        closeBeanFactory();}
    try {
        // createBeanFactory 方法直接新建一个 DefaultListableBeanFactory,内部使用的是 DefaultListableBeanFactory 实例
        DefaultListableBeanFactory beanFactory = createBeanFactory();
        // 设置序列化 id
        beanFactory.setSerializationId(getId());
        // 定制 beanFactory 工厂
        customizeBeanFactory(beanFactory);
        // 加载 BeanDefinition
        loadBeanDefinitions(beanFactory);
        synchronized (this.beanFactoryMonitor) {
            // 使用全局变量记录 BeanFactory
            this.beanFactory = beanFactory;
        }
    }
    catch (IOException ex) {throw new ApplicationContextException("I/O error parsing bean definition source for" + getDisplayName(), ex);
    }
}

看一下上述方法都做了什么:

  1. 判断 BeanFactory 是否存在,如果存在则销毁所有 Bean,然后关闭 BeanFactory;
  2. 使用 createBeanFactory 方法直接新建一个 DefaultListableBeanFactory,内部使用的是 DefaultListableBeanFactory 实例;
  3. 设置 BeanFactory 的设置序列化 id
  4. 定制 beanFactory 工厂,也就是给 allowBeanDefinitionOverriding(是否允许覆盖同名称的 Bean) 和 allowCircularReferences(是否允许 bean 存在循环依赖),可通过 setAllowBeanDefinitionOverriding 和 setAllowCircularReferences 赋值, 这里就可通过商编初始化方法中的 initPropertySources 方法来进行赋值;
  package lantao;
  import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyApplicationContext extends ClassPathXmlApplicationContext {public MyApplicationContext(String... configLocations){super(configLocations);
    }
    protected void initPropertySources(){
        // 添加验证要求
        getEnvironment().setRequiredProperties("VAR");
    
                // 在这里添加 set
        super.setAllowBeanDefinitionOverriding(true);
        super.setAllowCircularReferences(true);
    }
}
  1. 加载 BeanDefinition,就是解析 xml,循环解析,这里就不看了,如果不了解看作者上篇博客;
  • 下面看一下 prepareBeanFactory 方法源码:
/**
 * Configure the factory's standard context characteristics,
 * such as the context's ClassLoader and post-processors.
 * @param beanFactory the BeanFactory to configure
 */
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
    // Tell the internal bean factory to use the context's class loader etc.
    // 设置 BeanFactory 的 classLoader 为当前 context 的 classloader
    beanFactory.setBeanClassLoader(getClassLoader());

    // Spel 语言解析器
    // 设置 BeanFactory 的表达式语言处理器 Spring3 中增加了表达式语言的支持
    // 默认可以使用 #{bean.xxx} 的形式来调用相关属性值
    // 在 Bean 实例化的时候回调用 属性填充的方法 (doCreateBean 方法中的 populateBean 方法中的 applyPropertyValues 方法中的 evaluateBeanDefinitionString) 就会判断 beanExpressionResolver 是否为 null 操作
        beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));

    // 为 BeanFactory 增加一个默认的 PropertyEditor 这个主要对 bean 的属性等设置管理的一个工具 增加属性注册编辑器  例如:bean property 类型 date 则需要这里
    // beanFactory 会在初始化 BeanWrapper(initBeanWrapper)中调用 ResourceEditorRegistrar 的 registerCustomEditors 方法
    beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

    // Configure the bean factory with context callbacks.
    // ApplicationContextAwareProcessor --> postProcessBeforeInitialization
    // 注册 BeanPostProcessor  BeanPostProcessor 实在实例化前后执行的
    beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));

    // 设置几个忽略自动装配的接口 在 addBeanPostProcessor 方法中已经对下面几个类做了处理,他们就不是普通的 bean 了,所以在这里 spring 做 bean 的依赖的时候忽略
    // doCreateBean 方法中的 populateBean 方法中的 autowireByName 或 autowireByType 中的 unsatisfiedNonSimpleProperties 中的  !isExcludedFromDependencyCheck(pd) 判断,// 在属性填充的时候回判断依赖,如果存在下属几个则不做处理 对于下面几个类可以做 implements 操作
    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.
    // 设置几个注册依赖 参考 spring 源码深度解析原文:当注册依赖解析后,例如但那个注册了对 BeanFactory。class 的解析依赖后,当 bean 的属性注入的时候,一旦检测到属性为 BeanFactory 的类型变回将 beanFactory 实例注入进去
    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.
    // 寄存器早期处理器,用于检测作为 ApplicationListener 的内部 bean。beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));

    // Detect a LoadTimeWeaver and prepare for weaving, if found.
    // 增加了对 AxpectJ 的支持
    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.
    // 添加默认的系统环境 bean
    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());
    }
}

不说废话,直接看这个方法都做了什么:

  1. 设置 BeanFactory 的 classLoader 为当前 context 的 classloader;
  2. 设置 BeanFactory 的表达式语言处理器 Spring3 中增加了 Spel 表达式语言的支持, 默认可以使用 #{bean.xxx} 的形式来调用相关属性值,

    在 Bean 实例化的时候回调用 属性填充的方法 (doCreateBean 方法中的 populateBean 方法中的 applyPropertyValues 方法中的 evaluateBeanDefinitionString) 就会判断 beanExpressionResolver 是否为 null 操作,如果不是则会使用 Spel 表达式规则解析

    <?xml version="1.0" encoding="UTF-8" ?>
    <beans
           xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
    
        <bean id="testOneBean" class="lantao.bean.TestOneBean">
            <property name="testTwoBean" value="#{testTWoBean}"/>
        </bean>
        
        <bean id="testTWoBean" class="lantao.bean.TestTwoBean"/>
    
        <!-- 上面 相当于 下边 -->
    
        <bean id="testOneBean1" class="lantao.bean.TestOneBean">
            <property name="testTwoBean" ref="testTWoBean1"/>
        </bean>
    
        <bean id="testTWoBean1" class="lantao.bean.TestTwoBean"/>
    
    </beans>
    1. 为 BeanFactory 增加一个默认的 PropertyEditor 这个主要对 bean 的属性等设置管理的一个工具 增加属性注册编辑器 例如:User 类中 startDate 类型 date 但是 xml property 的 value 是 2019-10-10,在启动的时候就会报错,类型转换不成功,这里可以使用继承 PropertyEditorSupport 这个类机型重写并注入即可使用;beanFactory 会在初始化 BeanWrapper (initBeanWrapper) 中调用 ResourceEditorRegistrar 的 registerCustomEditors 方法进行初始化;
  3. 配置 BeanPostProcessor,这里配置的是 ApplicationContextAwareProcessor,上边我们说了,BeanPostProcessor 是在初始化方法 Init 前后执行,看一下 ApplicationContextAwareProcessor 的 Before 和 After 方法:
@Override
   @Nullable
   public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {
       AccessControlContext acc = null;
   
       // 该方法也会在 BeanFactory 实例化 bean 中调用  doCreateBean --> initializeBean --> applyBeanPostProcessorsBeforeInitialization --> postProcessBeforeInitialization
       // 如果实例化的类实现了 invokeAwareInterfaces 方法中的判断类 则会调用初始方法赋值
       if (System.getSecurityManager() != null &&
               (bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware ||
                       bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware ||
                       bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware)) {acc = this.applicationContext.getBeanFactory().getAccessControlContext();}
   
       if (acc != null) {AccessController.doPrivileged((PrivilegedAction<Object>) () -> {invokeAwareInterfaces(bean);
               return null;
           }, acc);
       }
       else {invokeAwareInterfaces(bean);
       }
           return bean;
   }
   private void invokeAwareInterfaces(Object bean) {if (bean instanceof Aware) {if (bean instanceof EnvironmentAware) {((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());
           }
           if (bean instanceof EmbeddedValueResolverAware) {((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.embeddedValueResolver);
           }
           if (bean instanceof ResourceLoaderAware) {((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
           }
           if (bean instanceof ApplicationEventPublisherAware) {((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);
           }
           if (bean instanceof MessageSourceAware) {((MessageSourceAware) bean).setMessageSource(this.applicationContext);
           }
           if (bean instanceof ApplicationContextAware) {((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
           }
       }
   }
   
   @Override
   public Object postProcessAfterInitialization(Object bean, String beanName) {return bean;}

在 Before 方法中调用了 invokeAwareInterfaces 方法,在 invokeAwareInterfaces 方法中做了类型 instanceof 的判断,意思就是如果这个 Bean 实现了上述的 Aware,则会初始会一下资源,比如实现了 ApplicationContextAware,就会 setApplicationContext,这里相信大家都用过,就不多说了;

    1. 设置几个忽略自动装配的接口 在 addBeanPostProcessor 方法中已经对下面几个类做了处理,他们就不是普通的 bean 了,所以在这里 spring 做 bean 的依赖的时候忽略,在 doCreateBean 方法中的 populateBean 方法中的 autowireByName 或 autowireByType 中的 unsatisfiedNonSimpleProperties 中的 !isExcludedFromDependencyCheck(pd) 判断,如果存在则不做依赖注入了;
    2. 设置几个注册依赖 参考 spring 源码深度解析原文:当注册依赖解析后,例如当注册了对 BeanFactory 的解析依赖后,当 bean 的属性注入的时候,一旦检测到属性为 BeanFactory 的类型便会将 beanFactory 实例注入进去;
    1. 添加 BeanPostProcessor,这里是添加 ApplicationListener,是寄存器早期处理器;这里可以看作者的源码测试,在 spring-context 的 test 测试类下有;
    2. 增加了对 AxpectJ 的支持
    3. 注册默认的系统环境 bean,environment,systemProperties,systemEnvironment;
    • 上述就是对 BeanFactory 的功能填充,下面看 postProcessBeanFactory:

    postProcessBeanFactory 方法是个空方法,允许在上下文子类中对 Bean 工厂进行后处理,例如:可以在这里进行 硬编码形式的 BeanFactoryPostProcessor 调用 addBeanFactoryPostProcessor,进行 addBeanFactoryPostProcessor 或者是 BeanPostProcessor;

    • 接下来看一下 invokeBeanFactoryPostProcessors 方法:
    public static void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
    
        // Invoke BeanDefinitionRegistryPostProcessors first, if any.
        Set<String> processedBeans = new HashSet<>();
    
        // 对 BeanDefinitionRegistry  类型处理
        if (beanFactory instanceof BeanDefinitionRegistry) {
            // 强转
            BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
    
            // 普通的处理器
            List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
    
            // 注册处理器
            List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
    
    
            // 这里就是硬编码处理 因为这里是从 getBeanFactoryPostProcessors() 方法获取的 可以硬编码从 addBeanFactoryPostProcessor()方法添加
            for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
    
                    // 对于 BeanDefinitionRegistryPostProcessor 类型 在 BeanFactoryPostProcessor 的基础上还有自己的定义,需要先调用
                    BeanDefinitionRegistryPostProcessor registryProcessor = (BeanDefinitionRegistryPostProcessor) postProcessor;
    
                    // 执行 继承 BeanDefinitionRegistryPostProcessor 类的  postProcessBeanDefinitionRegistry 方法
                    registryProcessor.postProcessBeanDefinitionRegistry(registry);
    
                    registryProcessors.add(registryProcessor);
                }
                else {regularPostProcessors.add(postProcessor);
                }
            }
            // 上边的 For 循环只是调用了硬编码的 BeanDefinitionRegistryPostProcessor 中的 postProcessBeanDefinitionRegistry 方法,// 但是 BeanFactoryPostProcessor 中的 postProcessBeanFactory 方法还没有调用,是在方法的最后一行
            // invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
            // invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory); 这两个方法中执行的,// 下面是自动处理器 获取类型是 BeanDefinitionRegistryPostProcessor  beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false); 获取的
    
    
            // 当前注册处理器
            List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
    
            // First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
            // 首先调用实现了 PriorityOrdered 的 BeanDefinitionRegistryPostProcessors
            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);
            // 执行 BeanDefinitionRegistryPostProcessor 类的 postProcessBeanDefinitionRegistry 方法
            invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
            currentRegistryProcessors.clear();
    
            // Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
            // 下一个,调用实现 Ordered 的 BeanDefinitionRegistryPostProcessors
            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);
            // 执行 BeanDefinitionRegistryPostProcessor 类的 postProcessBeanDefinitionRegistry 方法
            invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
            currentRegistryProcessors.clear();
    
            // Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
            // 最后,调用所有其他 BeanDefinitionRegistryPostProcessors,直到不再显示其他 BeanDefinitionRegistryPostProcessors 无序的
            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);
                // 执行 BeanDefinitionRegistryPostProcessor 类的 postProcessBeanDefinitionRegistry 方法
                    invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
                    currentRegistryProcessors.clear();}
    
            // 现在,调用到目前为止处理的所有处理器的  执行 BeanFactoryPostProcessor 类的 postProcessBeanFactory 方法
            // 这里执行的是 硬编码 和 非硬编码(自动)的 BeanFactoryPostProcessor 类的 postProcessBeanFactory 方法 分为硬编码处理器 和 普通处理器
            invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
            invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
        }
    
        else {
            // 调用在上下文实例中注册的工厂处理器的 postProcessBeanFactory 方法。就是硬编码 通过 addBeanFactoryPostProcessor 方法添加的 BeanFactoryPostProcessor
                invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
        }
    
    
    
    
        // 自动处理 非硬编码 获取类型为是 BeanFactoryPostProcessor    beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
    
        // 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.
    
        //  实现 priorityOrdered 的
        List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
    
        // 实现 Ordered 的
        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<>();
        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<>();
        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();}

    上述代码看起来很多,但是总计起来就三件事:

    1. 执行硬编码的和主动注入的 BeanDefinitionRegistryPostProcessor, 调用 postProcessBeanDefinitionRegistry 方法;
    2. 执行硬编码的和主动注入的 BeanFactoryPostProcessor,调用 postProcessBeanFactory 方法;
    3. 自动注入的可继承 Ordered 排序,priorityOrdered 排序或无序;

    上述测试在作者的 spring 源码 congtext 中 lantao 包下有测试用例;

    • registerBeanPostProcessors 方法源码:
    public static void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {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.
        int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
        beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
    
        // Separate between BeanPostProcessors that implement PriorityOrdered,
        // Ordered, and the rest.
        // 使用 priorityOrdered 保证顺序
        List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
    
        // MergedBeanDefinitionPostProcessor
        List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
    
        // 使用 order 保证顺序
        List<String> orderedPostProcessorNames = new ArrayList<>();
    
        // 无序的
        List<String> nonOrderedPostProcessorNames = new ArrayList<>();
    
        // 进行 add 操作
        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.
        // 首先 注册实现 PriorityOrdered 的 BeanPostProcessors 先排序 PostProcessors
        sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
        registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
    
        // Next, register the BeanPostProcessors that implement Ordered.
        // 下一个,注册实现 Ordered 的 BeanPostProcessors
        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);
    
        // Now, register all regular BeanPostProcessors.
        // 现在,注册所有常规注册。无序的
        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);
    
        // Finally, re-register all internal BeanPostProcessors.
        // 最后,注册所有 MergedBeanDefinitionPostProcessor 类型的 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).
        // 添加 ApplicationListener 探测器
        beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
    }

    registerBeanPostProcessors 方法代码还是比较长的,它和 invokeBeanFactoryPostProcessors 方法最主要的区别就是 registerBeanPostProcessors 只在这里注册,但不在这里调用,做的事情和 invokeBeanFactoryPostProcessors 差不多:

    1. 使用 priorityOrdered,Ordered 或无序保证顺序;
    2. 通过 beanFactory.addBeanPostProcessor(postProcessor) 进行注册;

    很简单,代码篇幅很长,但是很好理解,这里可以简单看一下;

    • 接下来是 initMessageSource 方法,这里作者没有过多的看源码,后续补上吧 …….(抱歉)
    • initApplicationEventMulticaster 源码:
    /**
     * Initialize the ApplicationEventMulticaster.
     * Uses SimpleApplicationEventMulticaster if none defined in the context.
     * @see org.springframework.context.event.SimpleApplicationEventMulticaster
     */
    protected void initApplicationEventMulticaster() {ConfigurableListableBeanFactory beanFactory = getBeanFactory();
        // 使用自定义的 广播
        if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
            this.applicationEventMulticaster =
                    beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
            if (logger.isTraceEnabled()) {logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
            }
        }
        else {
            // 使用 spring 默认的广播
            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() + "]");
            }
        }
    }

    initApplicationEventMulticaster 方法中主要就是判断是使用自定义的 ApplicationEventMulticaster(广播器) 还是使用呢 Spring 默认的 SimpleApplicationEventMulticaster 广播器;

    • onRefresh 方法是留个子类重写的,内容是空;
    • registerListeners 方法:
    /**
     * Add beans that implement ApplicationListener as listeners.
     * Doesn't affect other listeners, which can be added without being beans.
     */
    protected void registerListeners() {
        // Register statically specified listeners first.
        // 注册 添加 ApplicationListener  这里通过硬编码 addApplicationListener 方法添加的
        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!
        // 注册 添加 ApplicationListener 这里是自动注册添加的
        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);
            }
        }
    }

    registerListeners 方法做了三件事情:

    1. 添加 ApplicationListener 这里通过硬编码 addApplicationListener 方法添加的;
    2. 添加 ApplicationListener 是通过自动注册添加的
    3. 发布早起事件
    • finishBeanFactoryInitialization 方法源码:
    /**
     * Finish the initialization of this context's bean factory,
     * initializing all remaining singleton beans.
     */
    protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
        // Initialize conversion service for this context.
        // conversionService 用于类型转换,比如 String 转 Date
        // 判断 BeanFactory 中是否存在名称为“conversionService”且类型为 ConversionService 的 Bean,如果存在则将其注入到 beanFactory
        // 判断有无自定义属性转换服务接口,并将其初始化,我们在分析 bean 的属性填充过程中,曾经用到过该服务接口。在 TypeConverterDelegate 类的 convertIfNecessary 方法中
        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));
        }
    
        // 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.
        // 得到所有的实现了 LoadTimeWeaverAware 接口的子类名称,初始化它们
        // 如果有 LoadTimeWeaverAware 类型的 bean 则初始化,用来加载 Spring Bean 时织入第三方模块, 如 AspectJ,我们在后面详细讲解。String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
        for (String weaverAwareName : weaverAwareNames) {getBean(weaverAwareName);
        }
    
        // Stop using the temporary ClassLoader for type matching.
        // 停止使用临时类加载器 就是在这里不让使用呢 ClassLoader 了
        beanFactory.setTempClassLoader(null);
    
        // Allow for caching all bean definition metadata, not expecting further changes.
        // 冻结所有 bean 定义,说明你注册的 bean 将不被修改或进行任何进一步的处理 就是不让改了 BeanDefinition
        beanFactory.freezeConfiguration();
    
        // Instantiate all remaining (non-lazy-init) singletons.
        // 初始化所有非懒加载的 单例 bean  调用你 getBean 方法
        beanFactory.preInstantiateSingletons();}

    finishBeanFactoryInitialization 方法做了五件事情:

    1. 设置 BeanFactory 的 conversionService,conversionService 用于类型转换使用, 例如:User 类中 startDate 类型 date 但是 xml property 的 value 是 2019-10-10,在启动的时候就会报错,类型转换不成功,可以使用 conversionService;书中 170 页有具体代码;
    2. 添加 BeanFactory 的 addEmbeddedValueResolver,读取配置信息放到这里,可以通过 EmbeddedValueResolverAware 来获取,参考:https://www.cnblogs.com/winke…
    3. 得到所有的实现了 LoadTimeWeaverAware 接口的子类名称,初始化它们,用来加载 Spring Bean 时织入第三方模块, 如 AspectJ,我们在后面详细讲解。
    4. 停止使用临时类加载器 就是在这里不让使用呢 ClassLoader 了
    5. 冻结所有 bean 定义,说明你注册的 bean 将不被修改或进行任何进一步的处理 就是不让改了 BeanDefinition
    6. 初始化所有非懒加载的 单例 bean 调用你 getBean 方法,循环所有 bean 并实例化 条件是:单例,非 Abstract 非懒加载
    • 最后的一个方法 finishRefresh:
    /**
     * Finish the refresh of this context, invoking the LifecycleProcessor's
     * onRefresh() method and publishing the
     * {@link org.springframework.context.event.ContextRefreshedEvent}.
     */
    protected void finishRefresh() {// Clear context-level resource caches (such as ASM metadata from scanning).
        // 清除 下文级资源 (例如扫描的元数据)。clearResourceCaches();
        
        // Initialize lifecycle processor for this context.
        // 在当前 context 中初始化 lifecycle
        // lifecycle 有自己的 start/ stop 方法,实现此接口后 spring 保证在启动的时候调用 start 方法开始生命周期 关闭的时候调用 stop 方法结束生命周期
        initLifecycleProcessor();
    
        // Propagate refresh to lifecycle processor first.
        // onRefresh 启动所有实现了 lifecycle 的方法
        getLifecycleProcessor().onRefresh();
    
        // Publish the final event.
        // 当 ApplicationContext 初始化完成发布后发布事件 处理后续事宜
        publishEvent(new ContextRefreshedEvent(this));
    
        // Participate in LiveBeansView MBean, if active.
        // 这里 没明白》。。LiveBeansView.registerApplicationContext(this);
    }

    finishRefresh 方法是 ApplicationContext 初始化的最后一个方法了,他做了一些结尾的事情:

    1. 清除 下文级资源 (例如扫描的元数据)。
    2. 在当前 context 中初始化 lifecycle,lifecycle 有自己的 start/ stop 方法,实现此接口后 spring 保证在启动的时候调用 start 方法开始生命周期 关闭的时候调用 stop 方法结束生命周期。
    3. onRefresh 启动所有实现了 lifecycle 的方法,调用了 start 方法。
    4. 当 ApplicationContext 初始化完成发布事件 处理后续事宜。
    5. LiveBeansView.registerApplicationContext(this) 这个代码没有太明白,有大神可以留言;

    至此 ApplicationContext 的源码就都已经分析完成了,其中有很多地方很难懂,大家可以对应着源码一起看,会好理解一些,如果其中有错误,欢迎大神指点,在下方留言,本篇博客是作者参考 SPring 源码深度解析 + 自己的理解写出来的,算是一个学习后的的产出,最后,码字不易,转载请注明出处。

    博客地址:http://lantaoblog.site

    正文完
     0