美文网首页
Spring源码分析:Spring IOC容器核心流程源码解析

Spring源码分析:Spring IOC容器核心流程源码解析

作者: W998 | 来源:发表于2021-09-10 21:33 被阅读0次

    前言

    Spring图谱:


    Spring源码学习图谱.png

    简单介绍

    Spring IOC的核心方法就在于refresh方法,这个方法里面完成了Spring的初始化、准备bean、实例化bean和扩展功能的实现。

    • 这个方法的作用是什么?
    • 它是如何完成这些功能的?
    • 为什么要这样去实现?
    • 有哪些值得借鉴的地方?

    refresh方法

    在ConfigurableApplicationContext里面定义了这个方法:

    /**
     * Load or refresh the persistent representation of the configuration, which
     * might be from Java-based configuration, an XML file, a properties file, a
     * relational database schema, or some other format.
     * <p>As this is a startup method, it should destroy already created singletons
     * if it fails, to avoid dangling resources. In other words, after invocation
     * of this method, either all or no singletons at all should be instantiated.
     * @throws BeansException if the bean factory could not be initialized
     * @throws IllegalStateException if already initialized and multiple refresh
     * attempts are not supported
     */
    void refresh() throws BeansException, IllegalStateException;
    1.2.3.4.5.6.7.8.9.10.11.12.
    

    根据注释可以知道,这个方法是用来加载刷新配置,这些配置可能来自java配置、xml文件、properties文件、关系型数据库或者其他格式。

    作为一个启动方法,它应当在初始化失败后销毁已经创建的单例,防止占着资源而不使用。也就是说调用这个方法的话,要么所有的单例已经被实例化,要么所有的单例都不存在。

    BeansException:bean工厂不能被初始化,抛出BeansException

    IllegalStateException:bean工厂已经被初始化了,但是不支持多次刷新,抛出IllegalStateException

    具体实现

    在AbstractApplicationContext中进行了实现:

    @Override
    public void refresh() throws BeansException, IllegalStateException {
       synchronized (this.startupShutdownMonitor) {
          //为刷新做准备,初始化各种状态,启动时间、关闭激活状态、配置文件信息等
          prepareRefresh();
    
          //通知子类刷新内部BeanFactory,并返回刷新后的BeanFactory
          //关注方法中的refreshBeanFactory方法,两个子类对它重写的差异
          //AbstractRefreshableApplicationContext#refreshBeanFactory中重新构建,完成BeanDefinition的解析构建
          //GenericApplicationContext#refreshBeanFactory则是设置ID,并且只能刷新一次
          ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
    
          //给容器准备BeanFactory,配置相关的属性
          prepareBeanFactory(beanFactory);
    
          try {
             //允许子类处理后置beanFactory
             postProcessBeanFactory(beanFactory);
    
             //调用注册了beanFactory后置处理器接口实例bean对应的方法
             invokeBeanFactoryPostProcessors(beanFactory);
    
             //注册bean后置处理器接口的实例bean
             registerBeanPostProcessors(beanFactory);
    
             //初始化国际化资源
             initMessageSource();
    
             //初始化事件传播者
             initApplicationEventMulticaster();
    
             //refresh事件,初始化一些指定的bean
             onRefresh();
    
             //注册监听器bean
             registerListeners();
    
             //完成bean工厂的初始化,初始化所有非懒加载的单例bean
             finishBeanFactoryInitialization(beanFactory);
    
             //最后,发布finishRefresh事件
             finishRefresh();
          }
    
          catch (BeansException ex) {
             if (logger.isWarnEnabled()) {
                logger.warn("Exception encountered during context initialization - " +
                      "cancelling refresh attempt: " + ex);
             }
    
             //销毁了所有已经创建了的单例bean
             destroyBeans();
    
             //重置active标记
             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();
          }
       }
    }
    1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.28.29.30.31.32.33.34.35.36.37.38.39.40.41.42.43.44.45.46.47.48.49.50.51.52.53.54.55.56.57.58.59.60.61.62.63.64.65.66.67.
    

    使用示例:

    GenericApplicationContext context3 = new GenericApplicationContext();
    new XmlBeanDefinitionReader(context3).loadBeanDefinitions("classpath:application.xml");
    new ClassPathBeanDefinitionScanner(context3).scan("edu.demo");
    // 一定要刷新
    context3.refresh();
    1.2.3.4.5.
    

    IOC容器刷新整体流程

    prepareRefresh方法

    //关闭和刷新的状态都是AtomicBoolean类型的,原子性
    /** Flag that indicates whether this context is currently active. */
    private final AtomicBoolean active = new AtomicBoolean();
    
    /** Flag that indicates whether this context has been closed already. */
    private final AtomicBoolean closed = new AtomicBoolean();
    
    /**
     * 为容器刷新做准备,设置启动日期和活动标识
     * 并执行一些资源的初始化
     */
    protected void prepareRefresh() {
       //容器切换到启动状态
       //设置启动容器的时间
       this.startupDate = System.currentTimeMillis();
       //设置关闭的状态
       this.closed.set(false);
       //设置启动的状态
       this.active.set(true);
    
       if (logger.isDebugEnabled()) {
          if (logger.isTraceEnabled()) {
             logger.trace("Refreshing " + this);
          }
          else {
             logger.debug("Refreshing " + getDisplayName());
          }
       }
    
       //初始化容器的占位符资源
       initPropertySources();
    
       // 验证所有标记为required的属性都是可解析的:
       // see 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<>();
    }
    1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.28.29.30.31.32.33.34.35.36.37.38.39.40.41.42.43.44.45.46.47.48.49.50.51.
    

    obtainFreshBeanFactory方法

    /**
     * 告诉子类刷新内部的bean factory.
     * @return the fresh BeanFactory instance
     * @see #refreshBeanFactory()
     * @see #getBeanFactory()
     */
    protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
       refreshBeanFactory();
       return getBeanFactory();
    }
    1.2.3.4.5.6.7.8.9.10.
    

    其实就是配置用户的属性、加载bean定义,并且返回刷新后的bean工厂。prepareBeanFacotry方法内部又有两个抽象方法构成,交给子类去实现。也就是说子类必定含有一个BeanFactory实例,并且还需要提供刷新方法,返回BeanFactory实例的方法。

    具体实现类:

    1. AbstractRefreshableApplicationContext

    AbstractRefreshableApplicationContext中实现的刷新方法,可以被多次的调用执行,也就是可以多次刷新。

    /**
     * 实际的刷新方法。关闭以前的bean工厂,初始化一个新的bean工厂
     */
    @Override
    protected final void refreshBeanFactory() throws BeansException {
       //如果存在bean工厂,则销毁单例bean,关闭bean工厂
       if (hasBeanFactory()) {
          destroyBeans();
          closeBeanFactory();
       }
       try {
          //创建DefaultListableBeanFactory实例
          DefaultListableBeanFactory beanFactory = createBeanFactory();
          //设置ID
          beanFactory.setSerializationId(getId());
          //自定义bean工厂属性,bean定义重新、循环引用等配置
          customizeBeanFactory(beanFactory);
          //等待子类实现的,向bean工厂注册bean定义
          loadBeanDefinitions(beanFactory);
          //持有bean工厂的实例,以便在getBeanFactory方法中返回出去
          this.beanFactory = beanFactory;
       }
       catch (IOException ex) {
          throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
       }
    }
    
    //自定义bean工厂属性
    protected void customizeBeanFactory(DefaultListableBeanFactory beanFactory) {
       if (this.allowBeanDefinitionOverriding != null) {
          beanFactory.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
       }
       if (this.allowCircularReferences != null) {
          beanFactory.setAllowCircularReferences(this.allowCircularReferences);
       }
    }
    
    //关闭bean工厂的方法
    @Override
    protected final void closeBeanFactory() {
       DefaultListableBeanFactory beanFactory = this.beanFactory;
       //如果bean工厂存在
       if (beanFactory != null) {
          //设置ID为空
          beanFactory.setSerializationId(null);
          //设置bean工厂的实例为空
          this.beanFactory = null;
       }
    }
    1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.28.29.30.31.32.33.34.35.36.37.38.39.40.41.42.43.44.45.46.47.48.49.
    

    AbstractApplicationContext类中的销毁方法:

    //销毁方法
    protected void destroyBeans() {
       getBeanFactory().destroySingletons();
    }
    1.2.3.4.
    
    1. GenericApplicationContext

    GenericApplicationContext中的刷新方法,只能被调用一次,被AtomicBoolean类型的refreshed控制着

    private final AtomicBoolean refreshed = new AtomicBoolean();
    
    /**
     * 持有一个内部的bean工厂,通过公共的方法注册bean
     * @see #registerBeanDefinition
     */
    @Override
    protected final void refreshBeanFactory() throws IllegalStateException {
       //CAS的方式进行修改
       //多次刷新就抛出异常
       if (!this.refreshed.compareAndSet(false, true)) {
          throw new IllegalStateException(
                "GenericApplicationContext does not support multiple refresh attempts: just call 'refresh' once");
       }
       //设置ID
       this.beanFactory.setSerializationId(getId());
    }
    1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.
    

    beanFactory在构造函数中被创建的,代码如下:

    /**
     * Create a new GenericApplicationContext.
     * @see #registerBeanDefinition
     * @see #refresh
     */
    public GenericApplicationContext() {
       this.beanFactory = new DefaultListableBeanFactory();
    }
    
    /**
     * Create a new GenericApplicationContext with the given DefaultListableBeanFactory.
     * @param beanFactory the DefaultListableBeanFactory instance to use for this context
     * @see #registerBeanDefinition
     * @see #refresh
     */
    public GenericApplicationContext(DefaultListableBeanFactory beanFactory) {
       Assert.notNull(beanFactory, "BeanFactory must not be null");
       this.beanFactory = beanFactory;
    }
    1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.
    

    这个时候的beanFactory里面都有些什么呢?根据之前的注解的加载过程。可以知道,应该有BeanFactoryPostProcessor、BeanPostProcessor、ApplicationListener信息。

    prepareBeanFactory方法

    /**
     * 配置工厂的标准容器特征
     * 例如容器的ClassLoader和post-processor
     * @param beanFactory the BeanFactory to configure
     */
    protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
       // Tell the internal bean factory to use the context's class loader etc.
       //给bean工作准备ClassLoader、SPL表达式解析器、属性编辑注册器等
       beanFactory.setBeanClassLoader(getClassLoader());
       beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
       beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
    
       // Configure the bean factory with context callbacks.
       //向beanFactory注册ApplicationContextAwareProcessor
       //后面的六种Aware忽略他们的自动依赖注入
       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.
       //依赖需要使用的bean,IOC容器自己的多角色身份,@Autowried方式获得下列类型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.
       //注入ApplicationListeners接口实现的发现处理器,同时带有销毁、bean定义混合的实现
       beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
    
       // Detect a LoadTimeWeaver and prepare for weaving, if found.
       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.
       if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
          beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
       }
       if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
          // properties配置文件
          beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
       }
       if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
          // 操作系统环境变量:JAVA_HOME等
          beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
       }
    }
    1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.28.29.30.31.32.33.34.35.36.37.38.39.40.41.42.43.44.45.46.47.48.49.50.51.52.53.54.55.
    

    ApplicationContextAwareProcessor方法中的,注入Processor

    @Override
    @Nullable
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    //只针对EnvironmentAware、EmbeddedValueResolverAware、ResourceLoaderAware、ApplicationEventPublisherAware、MessageSourceAware、ApplicationContextAware 6种实现进行处理。
       if (!(bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware ||
             bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware ||
             bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware)){
          return bean;
       }
    
       AccessControlContext acc = null;
    
       if (System.getSecurityManager() != null) {
          acc = this.applicationContext.getBeanFactory().getAccessControlContext();
       }
    
       if (acc != null) {
          AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
             invokeAwareInterfaces(bean);
             return null;
          }, acc);
       }
       else {
          invokeAwareInterfaces(bean);
       }
    
       return bean;
    }
    
    //将beanFactory注入给上述的6种Aware
    private void invokeAwareInterfaces(Object bean) {
       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);
       }
    }
    1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.28.29.30.31.32.33.34.35.36.37.38.39.40.41.42.43.44.45.46.47.48.49.50.
    

    postProcessBeanFactory方法

    postProcessBeanFactory方法并没有去实现它。

    /**
     * Modify the application context's internal bean factory after its standard
     * initialization. All bean definitions will have been loaded, but no beans
     * will have been instantiated yet. This allows for registering special
     * BeanPostProcessors etc in certain ApplicationContext implementations.
     * @param beanFactory the bean factory used by the application context
     */
    protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
    }
    1.2.3.4.5.6.7.8.9.
    

    invokeBeanFactoryPostProcessors方法

    这个时候,bean工厂基本上已经准备完成,但是bean实例还没有进行初始化,接下来调用BeanFactoryPostProcessor对Bean工厂中的Bean定义进行调整

    /**
     * 执行BeanFactoryPostProcessor
     * <p>必须在单例bean实例化之前调用
     */
    protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
       //最重要的处理在委托里面实现
       //getBeanFactoryPostProcessors()获取的是容器里面的列表属性,
       //这个属性没有机会给外部去注入BeanFactoryPostProcessor对象。
       //因为ApplicationContext子类在构造函数中调用了refresh方法。所以这里是个空值
       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()));
       }
    }
    1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.
    

    invokeBeanFactoryPostProcessors方法:

    public static void invokeBeanFactoryPostProcessors(
          ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
    
       // Invoke BeanDefinitionRegistryPostProcessors first, if any.
       Set<String> processedBeans = new HashSet<>();
    
       if (beanFactory instanceof BeanDefinitionRegistry) {
          BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
          //BeanFactoryPostProcessor和BeanDefinitionRegistryPostProcessor
          List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
          List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
    
          for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
             if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
                //获取BeanDefinitionRegistryPostProcessor
                BeanDefinitionRegistryPostProcessor registryProcessor =
                      (BeanDefinitionRegistryPostProcessor) postProcessor;
                //这里既然做了处理,为何又加入到了registryProcessors集合中?   
                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.
          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);
          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);
          invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
          currentRegistryProcessors.clear();
    
          // Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
          //最后一步,处理没有优先顺序的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);
             invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
             currentRegistryProcessors.clear();
          }
    
          // Now, invoke the postProcessBeanFactory callback of all processors handled so far.
          //回调
          invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
          invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
       }
    
       else {
          // Invoke factory processors registered with the context instance.
          invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
       }
    
       // 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.
       //处理BeanFactoryPostProcessor,按照PriorityOrdered、Ordered和其他
       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.
       //第一步,处理继承自PriorityOrdered的BeanFactoryPostProcessors
       sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
       invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
    
       // Next, invoke the BeanFactoryPostProcessors that implement Ordered.
       //第二步,处理继承自Ordered的BeanFactoryPostProcessors
       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.
       //最后一步,处理其他的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();
    }
    1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.28.29.30.31.32.33.34.35.36.37.38.39.40.41.42.43.44.45.46.47.48.49.50.51.52.53.54.55.56.57.58.59.60.61.62.63.64.65.66.67.68.69.70.71.72.73.74.75.76.77.78.79.80.81.82.83.84.85.86.87.88.89.90.91.92.93.94.95.96.97.98.99.100.101.102.103.104.105.106.107.108.109.110.111.112.113.114.115.116.117.118.119.120.121.122.123.124.125.126.127.128.129.130.131.132.133.134.135.136.137.138.139.140.141.142.143.144.
    

    从上面的源码部分可以看到:

    • 拆成了两部分:registryProcessors、regularPostProcessors,分别处理BeanDefinitionRegistryPostProcessor和BeanFactoryPostProcessor
    • 排序处理:PriorityOrdered、Ordered和为排序的,按照这样的优先级进行处理

    多次调用了invokeBeanFactoryPostProcessors,因为在调用BeanFactoryPostProcessors的过程中,还会继续产生BeanFactoryPostProcessors,这里多次调用,就是为了处理掉所有的BeanFactoryPostProcessors。

    registerBeanPostProcessors方法

    到了这一步,bean定义已经加载完成,bean工厂完成了刷新和实例化,而且通过BeanFactoryProcessor修整了bean定义信息,接下来注册BeanPostProcessors

    /**
     * Instantiate and register all BeanPostProcessor beans,
     * respecting explicit order if given.
     * <p>Must be called before any instantiation of application beans.
     */
    protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
       PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
    }
    1.2.3.4.5.6.7.8.
    

    PostProcessorRegistrationDelegate的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.
       List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
       List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
       List<String> orderedPostProcessorNames = new ArrayList<>();
       List<String> nonOrderedPostProcessorNames = new ArrayList<>();
       for (String ppName : postProcessorNames) {
          if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
             BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
             priorityOrderedPostProcessors.add(pp);
             if (pp instanceof MergedBeanDefinitionPostProcessor) {
                internalPostProcessors.add(pp);
             }
          }
          else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
             orderedPostProcessorNames.add(ppName);
          }
          else {
             nonOrderedPostProcessorNames.add(ppName);
          }
       }
    
       // 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.
       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).
       beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
    }
    1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.28.29.30.31.32.33.34.35.36.37.38.39.40.41.42.43.44.45.46.47.48.49.50.51.52.53.54.55.56.57.58.59.60.61.62.63.64.65.66.67.68.
    

    可以看到上面的源码部分,和与BeanFactroyPostProcessor的处理简直一样,排序然后调用处理逻辑。

    1. priorityOrderedPostProcessors
    2. orderedPostProcessors
    3. nonOrderedPostProcessors
    4. internalPostProcessors
    5. ApplicationListenerDetector

    下面是排序的实例:

    • 没有继承任何排序的接口:
    @Component
    public class MyBeanDefinitonRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {
    
       @Override
       public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
          System.out.println("--- MyBeanDefinitonRegistryPostProcessor.postProcessBeanFactory 被执行了。");
    
       }
    
       @Override
       public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
          System.out.println("--- MyBeanDefinitonRegistryPostProcessor.postProcessBeanDefinitionRegistry 被执行了。");
       }
    
    }
    1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.
    
    • 继承Ordered接口:
    @Component
    public class MyBeanDefinitonRegistryPostProcessor2 implements BeanDefinitionRegistryPostProcessor, Ordered {
    
       @Override
       public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
          System.out.println("--- MyBeanDefinitonRegistryPostProcessor2.postProcessBeanFactory 被执行了。");
    
       }
    
       @Override
       public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
          System.out.println("--- MyBeanDefinitonRegistryPostProcessor2.postProcessBeanDefinitionRegistry 被执行了。");
       }
    
       @Override
       public int getOrder() {
          return 0;
       }
    }
    1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.
    
    • 继承PriorityOrdered接口:
    @Component
    public class MyBeanDefinitonRegistryPostProcessor3 implements BeanDefinitionRegistryPostProcessor, PriorityOrdered {
    
       @Override
       public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
          System.out.println("--- MyBeanDefinitonRegistryPostProcessor3.postProcessBeanFactory 被执行了。");
    
       }
    
       @Override
       public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
          System.out.println("--- MyBeanDefinitonRegistryPostProcessor3.postProcessBeanDefinitionRegistry 被执行了。");
       }
    
       @Override
       public int getOrder() {
          return 1;
       }
    }
    1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.
    

    执行结果如下:

    ![解析ps:https://img.haomeiwen.com/i25159600/321b5b98a7566dde?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

    从上图可以清楚的看到,PriorityOrdered > Ordered > 未排序

    initMessageSource方法

    此时BenPostProcessor都已经注册完成,下一步就是准备国际化资源:

    /**
     * 初始化国际化资源,如果没有,就使用父类的
     */
    protected void initMessageSource() {
       //获取bean工厂
       ConfigurableListableBeanFactory beanFactory = getBeanFactory();
       //如果Bean工厂中存在名为messageSource的bean,则使用它
       if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
          this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
          // Make MessageSource aware of parent MessageSource.
          //获取父类的MessageSource
          if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
             HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
             if (hms.getParentMessageSource() == null) {
                // Only set parent context as parent MessageSource if no parent MessageSource
                // registered already.
                hms.setParentMessageSource(getInternalParentMessageSource());
             }
          }
          if (logger.isTraceEnabled()) {
             logger.trace("Using MessageSource [" + this.messageSource + "]");
          }
       }
       else {
          // Use empty MessageSource to be able to accept getMessage calls.
          //使用DelegatingMessageSource作为国际化资源处理bean
          DelegatingMessageSource dms = new DelegatingMessageSource();
          dms.setParentMessageSource(getInternalParentMessageSource());
          this.messageSource = dms;
          beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
          if (logger.isTraceEnabled()) {
             logger.trace("No '" + MESSAGE_SOURCE_BEAN_NAME + "' bean, using [" + this.messageSource + "]");
          }
       }
    }
    1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.28.29.30.31.32.33.34.35.
    

    简单的例子:
    在application.properties配置如下信息:

    logging.config=classpath:logback.xml
    my.love=java
    1.2.
    
    @Configuration
    @PropertySource("classpath:/application.properties")
    public class MessageConfiguration {
    
       @Bean("messageSource")
       public ReloadableResourceBundleMessageSource getReloadableResourceBundleMessageSource() {
          ReloadableResourceBundleMessageSource rms = new ReloadableResourceBundleMessageSource();
          rms.setBasename("message");
          return rms;
       }
    }
    1.2.3.4.5.6.7.8.9.10.11.
    
    @MyComponetAnno
    public class MessageBean {
    
       @Autowired
       private ApplicationContext applicationContext;
    
       public MessageBean() {
          System.out.println("-----------------Abean 被实例化了。。。。。。。。。");
       }
    
       public void doSomething() {
          System.out.println(this + " do something .....my.love="
                + this.applicationContext.getEnvironment().getProperty("my.love"));
          System.out
                .println("-----------project.name=" + 
                      this.applicationContext.getMessage("project.name", null, Locale.CHINA));
       }
    }
    1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.
    
    public class MessageStarter {
    
       public static void main(String[] args) {
          // 注解方式,指定扫描的包
          AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
                "edu.demo.spring.message");
          MessageBean bean = context.getBean(MessageBean.class);
          bean.doSomething();
          context.close();
    
       }
    }
    1.2.3.4.5.6.7.8.9.10.11.12.
    

    输出如下:

    image

    initApplicationEventMulticaster方法

    下面就是初始化事件多播器:

    /**
     * 初始化ApplicationEventMulticaster.
     * Uses SimpleApplicationEventMulticaster if none defined in the context.
     * @see org.springframework.context.event.SimpleApplicationEventMulticaster
     */
    protected void initApplicationEventMulticaster() {
       //获取bean工厂
       ConfigurableListableBeanFactory beanFactory = getBeanFactory();
       //如果bean工厂中包含applicationEventMulticaster,就使用它
       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 {
          //使用SimpleApplicationEventMulticaster
          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() + "]");
          }
       }
    }
    1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.
    

    onRefresh方法

    没有子类进行实现

    /**
     * Template method which can be overridden to add context-specific refresh work.
     * Called on initialization of special beans, before instantiation of singletons.
     * <p>This implementation is empty.
     * @throws BeansException in case of errors
     * @see #refresh()
     */
    protected void onRefresh() throws BeansException {
       // For subclasses: do nothing by default.
    }
    1.2.3.4.5.6.7.8.9.10.
    

    registerListeners方法

    接下来,检查事件监听器,并注册到事件传播器上

    /**
     *  在不生成Bean对象的情况下添加ApplicationListener bean作为监听器
     * 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.
       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 (!CollectionUtils.isEmpty(earlyEventsToProcess)) {
          for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
             getApplicationEventMulticaster().multicastEvent(earlyEvent);
          }
       }
    }
    1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.
    

    事件广播器执行的方法:
    SimpleApplicationEventMulticaster的multicastEvent(ApplicationEvent, ResolvableType)方法:

    @Override
    public void multicastEvent(ApplicationEvent event) {
       multicastEvent(event, resolveDefaultEventType(event));
    }
    
    @Override
    public void multicastEvent(final ApplicationEvent event, @Nullable ResolvableType eventType) {
       ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event));
       Executor executor = getTaskExecutor();
       for (ApplicationListener<?> listener : getApplicationListeners(event, type)) {
          if (executor != null) {
             executor.execute(() -> invokeListener(listener, event));
          }
          else {
             invokeListener(listener, event);
          }
       }
    }
    1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.
    

    finishBeanFactoryInitialization方法

    完成bean工厂的初始化,将bean工厂中,非懒加载的单例bean进行实例化

    这一部分将在后面的文章中进行分析

    /**
     * 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.
       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.
       String[] weaverAwareNames = beanFactory.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.
       beanFactory.freezeConfiguration();
    
       // Instantiate all remaining (non-lazy-init) singletons.
       beanFactory.preInstantiateSingletons();
    }
    1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.28.29.30.31.32.33.34.
    

    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.
       //初始化容器的生命周期处理器
       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);
    }
    1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.
    

    容器的关闭:

    AbstractApplicationContext#close

    AbstractApplicationContext#registerShutdownHook

    AbstractApplicationContext#doClose

    整体流程图如下:

    image

    相关文章

      网友评论

          本文标题:Spring源码分析:Spring IOC容器核心流程源码解析

          本文链接:https://www.haomeiwen.com/subject/dpinwltx.html