Spring的核心模块:容器刷新refresh原理解析(三万字整理!)。

Refresh原理解析

  • 前言
    • 简单介绍
      • 为什么会有这个方法的存在
    • 框架介绍(宏观介绍)

前言

前面我们聊过bean的生命周期,也涉及到了一些容器的初始化,那么现在我们就来一起聊聊Spring框架中当之无愧的炸子鸡之一的AbstractApplicationContext类下的Refresh方法。
其难度之大,逻辑之复杂,写这篇文章的时候很头大:经常会有盲目深入导致自己理解不了,逻辑盘不明白;简单的浅入又觉得有点遗憾,本篇结合原理和源码,由宏观到细微之处,尽自己全力来发现refresh里面的巧妙。
如果你觉得看完本篇有帮助,可以点个关注交个朋友,以后也希望为你带来更多有益的文章。

目前文章还未完成,成品大概在5万字左右,为了防止我看不到忘记,先发表出来,慢慢的去盘清楚这部分内容,内容比较多,请理解一下。

简单介绍

refresh() 方法是 Spring 框架中最为核心的方法之一,可以说整个 Spring 容器的运作机制就是围绕着这个方法来展开的,在Spring框架中,ApplicationContext是容器的核心接口,负责管理和维护Spring应用程序中的所有bean。
当应用程序启动时,Spring容器会自动创建并加载所有的bean定义,并将其实例化为bean对象。随着应用程序的运行,这些bean对象可能需要被修改、替换、删除等操作,这时就需要刷新ApplicationContext来更新bean的状态。

为什么会有这个方法的存在

当一个应用程序启动时,Spring IoC容器会初始化并创建所有的bean实例,这些bean实例通常包括数据访问对象、业务对象、控制器等。
举个例子来分别展示一下这三个是什么:
1.数据访问对象(DAO)
假设我们需要访问数据库中的用户信息,我们可以定义一个UserDao接口和UserDaoImpl实现类,如下所示:

public interface UserDao {
    List<User> getAllUsers();
}
@Repository (@Repository注解是用于标识该类为数据访问对象(DAO)的注解,它的作用是告诉Spring容器该类的作用以及如何使用该类。)
public class UserDaoImpl implements UserDao {
    @Autowire
    private JdbcTemplate jdbcTemplate;

    public UserDaoImpl(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
    @Override
    public List<User> getAllUsers() {
        String sql = "SELECT * FROM users";
        return jdbcTemplate.query(sql, new UserRowMapper());
    }
}
  1. 业务对象(Service)
    编写一个用户管理的业务逻辑,我们可以定义一个UserService接口和UserServiceImpl实现类,如下所示:
public interface UserService {
    List<User> getAllUsers();
}
@Service
public class UserServiceImpl implements UserService {
    @Autowire
    private  UserDao userDao;

    public UserServiceImpl(UserDao userDao) {
        this.userDao = userDao;
    }
    @Override
    public List<User> getAllUsers() {
        return userDao.getAllUsers();
    }
}

3.控制器(Controller)
我们可以定义一个UserController控制器类,如下所示:

@RestController
@RequestMapping("/users")
public class UserController {
    @Autowire
    private  UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }
    @GetMapping
    public List<User> getAllUsers() {
        return userService.getAllUsers();
    }
}

在应用程序运行期间,如果需要更改bean的属性或者添加新的bean,就需要将这些变化更新到IoC容器中。
这时候,就需要使用Spring框架中提供的refresh()方法来重新加载配置文件、更新bean的定义、实例化和注册bean,以保证容器中的bean与最新的配置文件保持一致
当我们调用refresh()方法时,IoC容器会先销毁容器中的所有bean,然后重新读取配置文件,更新容器中的bean定义信息,并重新实例化和注册bean。
这个过程可以保证应用程序运行期间,容器中的bean信息都是最新的,同时也可以保证容器中的bean的状态与配置文件保持一致。
这个过程也被称为IoC容器的刷新过程。

框架介绍(宏观介绍)

介绍的思路是:主要的方法+文字解释,一些太难的方法因本人能力有限,会做个预埋,后面有能力的再来补上。
整个refresh方法的重点方法:

1.preareRefresh————刷新前的工作准备
 1.1:initPropertySources————校验Environment的requiredProperties是否都存在
  1.1.1:AbstractRefreshableWebApplicationContext
默认不做任何实现。
  1.1.2:GenericWebApplication
  1.1.3:StaticWebApplicationContext
 1.2:earlyApplicationListeners————监听器
2.obtainFreshBeanFactory————获取子类刷新后的内容beanFactory实例,它的作用是创建并刷新容器的bean工厂,包括从上下文定义的位置加载bean定义、创建bean工厂实例、设置bean工厂的序列化id等。
 2.1:refreshBeanFactory————刷新beanFactory。
3.prepareBeanFactory——为容器注册必要的系统级别的Bean4.postProcessBeanFactory——允许容器的子类去注册postProcessor。
  4.1.AbstractRefreshableWebApplicationContext。
  4.2

一:preareRefresh:刷新前的工作准备

   protected void prepareRefresh() {  
   // Switch to active.  
   //设置启动时间  
   this.startupDate = System.currentTimeMillis();  
   this.closed.set(false);  
   //设置容器的状态为激活  
   this.active.set(true);  
       //配置的日志w等级决定是否详细记录  
   if (logger.isDebugEnabled()) {  
      if (logger.isTraceEnabled()) {  
         logger.trace("Refreshing " + this);  
      }  
      else {  
         logger.debug("Refreshing " + getDisplayName());  
      }  
   }  
  
   // Initialize any placeholder property sources in the context environment.  
   //初始化Environment的propertySources属性  
   //样例  
   //3.校验Environment的requiredProperties是否都存在  
   initPropertySources();  
  
   // Validate that all properties marked as required are resolvable:  
   // 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<>();  
  }

进入到initPropertySources:

protected void initPropertySources() {  
   // For subclasses: do nothing by default.  
}
//这个一个空方法,下面与三个实现:
1.AbstractRefreshableWebApplicationContext

/**AbstractRefreshableWebApplicationContext是一个抽象类,它扩展了AbstractRefreshableApplicationContext并添加了一些Web应用程序特定的功能。该类的主要作用是提供一个可刷新的Web应用程序上下文,用于管理应用程序中的bean。

具体来说,AbstractRefreshableWebApplicationContext提供了以下功能:

1.  支持自动刷新功能,允许在应用程序运行时重新加载配置文件,并重新实例化和注册bean。
通过继承 `AbstractRefreshableConfigApplicationContext`,该类已经实现了自动刷新的功能。
通过实现 ConfigurableApplicationContext 接口中的 refresh() 方法实现自动刷新的。在 refresh() 方法中,它会执行以下操作:

1.  创建或刷新环境(environment)属性
在`AbstractApplicationContext#refresh()`方法中,调用`ConfigurableEnvironment#merge(ConfigurableEnvironment parent)`方法合并父子环境属性。
2.  初始化或更新 bean 工厂
在`AbstractApplicationContext#refresh()`方法中,通过调用`refreshBeanFactory()`方法来初始化或更新bean工厂。
3.  注册 bean 后处理器
在`AbstractApplicationContext#registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory)`方法中,通过注册不同类型的`BeanPostProcessor`实现类,完成bean后处理器的注册。
4.  提供对应用程序事件的发布
在`AbstractApplicationContext#publishEvent(ApplicationEvent event)`方法中,将应用程序事件发布到已注册的所有应用程序侦听器。
5.创建或刷新单例 bean 实例
在`AbstractBeanFactory#doGetBean(String name, Class requiredType, Object[] args, boolean typeCheckOnly)`方法中,首先从singletonObjects缓存中查找bean实例,如果没有找到则调用`createBean()`方法创建bean实例,并将其加入到singletonObjects缓存中,完成单例bean的创建或刷新。


初始化或更新 bean 工厂的过程涉及到 AbstractRefreshableConfigApplicationContext 子类实现的 postProcessBeanFactory() 方法,该方法会在 bean 工厂创建完成后调用。在这个方法中,子类可以添加自己的后处理器,注册自定义的作用域等。如果 AbstractRefreshableConfigApplicationContext 检测到应用程序上下文的定义已经被更改,它将自动刷新上下文,并重新加载所有 bean 定义,并根据需要重新创建 bean 实例。

因此,AbstractRefreshableConfigApplicationContext 实现了自动刷新的功能。
    
2.  提供对Servlet环境的支持,允许将Web应用程序上下文与Servlet API相关联,以便可以在Web应用程序中使用Servlet API。
-   `private ServletContext servletContext;`和 `private ServletConfig servletConfig;`两个属性用于存储当前应用程序运行的 Servlet 环境相关的上下文和配置信息。
-   `setServletContext()` 和 `getServletContext()` 方法用于设置和获取 Servlet 上下文。
-   `setServletConfig()` 和 `getServletConfig()` 方法用于设置和获取 Servlet 配置。
    
3.  提供对Spring Web MVC的支持,允许将Web应用程序上下文与Spring Web MVC相关联,以便可以在Web应用程序中使用Spring Web MVC。
-   `postProcessBeanFactory()` 方法中注册了一个 `ServletContextAwareProcessor`,该处理器用于处理实现了 `ServletContextAware` 接口的 bean,以便让这些 bean 可以访问 Servlet 环境相关的上下文和配置信息。
-   `getResourceByPath()` 和 `getResourcePatternResolver()` 两个方法用于支持在Web应用程序中使用Spring Web MVC,让应用程序可以使用 Servlet 环境相关的上下文访问资源。
    
4.  提供对Spring Security的支持,允许将Web应用程序上下文与Spring Security相关联,以便可以在Web应用程序中使用Spring Security。
    该类没有直接提供 Spring Security 相关的支持,但是可以将 Spring Security 的相关配置文件集成到 Web 应用程序上下文中,并重新加载配置文件以实现动态更新。

总之,AbstractRefreshableWebApplicationContext是一个可刷新的Web应用程序上下文,提供了许多与Web应用程序相关的功能,用于管理Spring应用程序中的bean。**/
2.GenericWebApplicationContext

3.StaticWebApplicationContext

二:obtainFreshBeanFactory:获取子类刷新后的内容

 * 该方法的作用是获取最新的ConfigurableListableBeanFactory实例。
 * 方法内部,调用refreshBeanFactory方法来刷新当前Application的BeanFactory,
 * 并获取刷新后的BeanFactory实例,
 * 通过getBeanFactory方法获取BeanFactory并返回。
 * 因为BeanFactory是Spring IoC容器中管理bean的核心接口,
 * 因此在应用程序启动时,需要确保BeanFactory实例是最新的,以便管理所有的bean。

代码如下:

protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
		refreshBeanFactory();
		return getBeanFactory();
	}

beanFactory实例

 //告诉子类启动refreshBeanFactory方法,Bean定义资源文件的载入从子类的refreshBeanFactory()方法启动,  
 //里面有抽象方法针对xml配置,最终创建内部容器,该容器负责Bean的创建与管理,  
 //在这一步会进行BeanDefinition的注册。  
 ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

进去obtainFreshBeanFactory后:

protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {  
  refreshBeanFactory();  
  return getBeanFactory();  
}

进入到refreshBeanFactory后:

protected abstract void refreshBeanFactory() throws BeansException, IllegalStateException;
protected final void refreshBeanFactory() throws BeansException {  
  if (hasBeanFactory()) {  
     destroyBeans();  
     closeBeanFactory();  
  }  
  try {  
     DefaultListableBeanFactory beanFactory = createBeanFactory();  
     beanFactory.setSerializationId(getId());  
     customizeBeanFactory(beanFactory);  
     loadBeanDefinitions(beanFactory);  
     this.beanFactory = beanFactory;  
  }  
  catch (IOException ex) {  
     throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);  
  }  
}

三:prepareBeanFactory:注册一些容器中需要的Bean。

protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {  
   // Tell the internal bean factory to use the context's class loader etc.  
   //告诉内部bean工厂使用容器的类加载器  
   beanFactory.setBeanClassLoader(getClassLoader());  
   //设置beanFactory的表达式语言处理器,Spring3开始增加  
   //对语言表达式的支持,默认可以使用#{bean.xxx}的形式来调用相关属性值  
   beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));  
    //为beanFactory增加一个默认的propertyEditor  
   beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));  
  
   // Configure the bean factory with context callbacks.  
   // 添加该处理器的作用:当应用程序定义的Bean实现ApplicationContextAware接口时  
   // 注入ApplicationContext对象  
   beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));  
   //如果某个bean依赖以下几个接口的实现类,在自动装配的时候忽视它们  
   //Spring会通过其他方式来处理依赖。  
   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 class接口的实现类,  
   //则在运行时修指定为当前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.  
   //注册早期后置处理器,用于检测内部bean作为应用程序监听器。  
   //ApplicationListenerDetector的作用就是判断某个Bean是否为ApplicationListener  
   // 如果是,加入到事件监听者队列  
   beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));  
  
   // Detect a LoadTimeWeaver and prepare for weaving, if found.  
   //如果找到一个LoadTimeWeaver,那么就准备将后置处理器,"织入"bean工厂。  
   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.  
   //注册默认environment环境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());  
   }  
}

四:postProcessBeanFactory:允许容器的子类去注册postProcessor——钩子方法

protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {  
}

五: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()));  
   }  
}

进入invokeBeanFactoryPostProcessors方法中:

public static void invokeBeanFactoryPostProcessors(  
      ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {  
  
   // Invoke BeanDefinitionRegistryPostProcessors first, if any.  
   //如果有BeanDefinitionRegistryPostProcessor的话优先执行  
   Set<String> processedBeans = new HashSet<>();  
   //如果是BeanDefinitionRegistry类型的话  
   if (beanFactory instanceof BeanDefinitionRegistry) {  
  
      BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;  
      //用于记录常规BeanFactoryPostProcessor  
      List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();  
      //用于记录常规BeanDefinitionRegistryPostProcessor  
      List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();  
           //遍历所有参数传递进来的BeanFactoryPostProcessor(它们并没有作为bean注册在容器中)  
      //将所有参数传入的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.      List currentRegistryProcessors = new ArrayList<>();  
  
      // First, invoke the BeanDefinitionRegistryPostProcessors that implement 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();  
  
      // Next, invoke the BeanDefinitionRegistryPostProcessors that implement 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.  
      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.   List 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();  
}

六:registerBeanPostProcessors:调用容器注册的容器级别的后置处理器

protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {  
   PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);  
}

进入到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 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));  
}

七:initMessageSource——初始化国际化配置

protected void initMessageSource() {  
   ConfigurableListableBeanFactory beanFactory = getBeanFactory();  
   if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {  
      this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);  
      // Make MessageSource aware of parent 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 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 + "]");  
      }  
   }  
}

八:initApplicationEventMulticaster——初始化事件发布者组件

protected void initApplicationEventMulticaster() {  
   ConfigurableListableBeanFactory beanFactory = getBeanFactory();  
   //如果容器存在ApplicationEventMulticaster的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  
      //并完成SimpleApplicationEventMulticaster Bean的注册  
      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() + "]");  
      }  
   }  
}

进入到multicastEvent

@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);  
      }  
   }  
}

九:
十:
十一:finishBeanFactoryInitialization

protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {  
   // Initialize conversion service for this context.  
   //初始化此容器的转换器。  
   //转换器的职责是处理通过配置给Bean实例成员变量赋值的时候的类型转换工作。  
   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.   //如果没有注册过bean后置处理器post-processor,则注册默认的解析器。  
   //(例如主要用于解析properties文件的PropertyPlaceholderConfigurer)  
   //@value注解或在xml中使用${}的方式进行环境相关的配置。  
   if (!beanFactory.hasEmbeddedValueResolver()) {  
      beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));  
   }  
  
   // Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.  
   //AOP分为三种方式:编译期织入,类加载期织入和运行期织入。  
   //LoadTimeWeaving属于第二种,主要通过JVM进行织入。  
   //先初始化LoadTimeWeaverAware bean,以便尽早注册它们的transformers  
   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.  
   //允许缓存所有bean定义元数据,不希望有进一步的更改  
   beanFactory.freezeConfiguration();  
  
   // Instantiate all remaining (non-lazy-init) singletons.  
   //实例化所有剩余的(non-lazy-init非延时加载的)单例  
   beanFactory.preInstantiateSingletons();  
}

进入:preInstantiateSingletons()

public void preInstantiateSingletons() throws BeansException {  
   if (logger.isTraceEnabled()) {  
      logger.trace("Pre-instantiating singletons in " + this);  
   }  
  
   // Iterate over a copy to allow for init methods which in turn register new bean definitions.  
   // While this may not be part of the regular factory bootstrap, it does otherwise work fine.   List beanNames = new ArrayList<>(this.beanDefinitionNames);  
  
   // Trigger initialization of all non-lazy singleton beans...  
   for (String beanName : beanNames) {  
      RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);  
      if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {  
         if (isFactoryBean(beanName)) {  
            Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);  
            if (bean instanceof FactoryBean) {  
               FactoryBean<?> factory = (FactoryBean<?>) bean;  
               boolean isEagerInit;  
               if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {  
                  isEagerInit = AccessController.doPrivileged(  
                        (PrivilegedAction<Boolean>) ((SmartFactoryBean<?>) factory)::isEagerInit,  
                        getAccessControlContext());  
               }  
               else {  
                  isEagerInit = (factory instanceof SmartFactoryBean &&  
                        ((SmartFactoryBean<?>) factory).isEagerInit());  
               }  
               if (isEagerInit) {  
                  getBean(beanName);  
               }  
            }  
         }  
         else {  
            getBean(beanName);  
         }  
      }  
   }  
  
   // Trigger post-initialization callback for all applicable beans...  
   for (String beanName : beanNames) {  
      Object singletonInstance = getSingleton(beanName);  
      if (singletonInstance instanceof SmartInitializingSingleton) {  
         SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;  
         if (System.getSecurityManager() != null) {  
            AccessController.doPrivileged((PrivilegedAction<Object>) () -> {  
               smartSingleton.afterSingletonsInstantiated();  
               return null;            }, getAccessControlContext());  
         }  
         else {  
            smartSingleton.afterSingletonsInstantiated();  
         }  
      }  
   }  
}

你可能感兴趣的:(Spring源码解析,spring,java,mybatis)