spring源码(二)beanFactory预处理

679 阅读3分钟

这是我参与8月更文挑战的第6天,活动详情查看:8月更文挑战

前言

上一篇已经介绍了spring容器初始化的大概流程,这次对其中的一些流程进行仔细分析。

正文

这次分析spring容器创建流程中的前几个流程:


    //所在类及方法:AbstractApplicationContext.refresh()
            // Prepare this context for refreshing.
         prepareRefresh();

         // Tell the subclass to refresh the internal bean factory.
         ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

         // Prepare the bean factory for use in this context.
         prepareBeanFactory(beanFactory);

prepareRefresh

方法上面的注释也写得很明白:为刷新准备上下文,进方法源码:

    //所在类及方法:AbstractApplicationContext.prepareRefresh()
    protected void prepareRefresh() {
      this.startupDate = System.currentTimeMillis(); // 记录启动时间
      this.closed.set(false); // 设置容器关闭状态为false
      this.active.set(true); // 设置容器活跃状态为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();// 初始化PropertySources

      // Validate that all properties marked as required are resolvable:
      // see ConfigurablePropertyResolver#setRequiredProperties
      getEnvironment().validateRequiredProperties(); // 校验获得的Property

      // Store pre-refresh ApplicationListeners... 
        // 初始化存储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...
        // 初始化存储earlyApplicationEvents
      this.earlyApplicationEvents = new LinkedHashSet<>();
   }

这个方法相对来说做的事情是比较简单的,都是前期的一些准备, 就是初始化this.startupDate ,this.closed.set(false),this.active.set(true),applicationListeners,earlyApplicationListeners,earlyApplicationEvents这些属性。

注意点就是其中的initPropertySources这个方法,该方法默认是没有什么动作的,不过在spring-web包下有三个类实现了该方法。

obtainFreshBeanFactory方法

这个方法的源码也比较简单:


    // 所在类及方法:AbstractApplicationContext.obtainFreshBeanFactory
    protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
        // 刷新BeanFactory
      refreshBeanFactory();
        // 返回
      return getBeanFactory();
   }

在AbstractApplicationContext类中,上面的两个方法都是接口,从上篇文章中,使用的是AnnotationConfigApplicationContext,从类继承图可以知道, GenericApplicationContext类对上述两个方法有实现,直接定位至GenericApplicationContext类:


    // 所在类:GenericApplicationContext
    @Override
   protected final void refreshBeanFactory() throws IllegalStateException {
      if (!this.refreshed.compareAndSet(false, true)) { //cas修改refreshed状态
         throw new IllegalStateException(
               "GenericApplicationContext does not support multiple refresh attempts: just call 'refresh' once");
      }
      this.beanFactory.setSerializationId(getId());
   }

    @Override
   public final ConfigurableListableBeanFactory getBeanFactory() {
      return this.beanFactory;
   }

上述两个方法都是比较简单的,

  1. refreshBeanFactory方法使用cas修改refreshed值,将其修改为true,最后再给beanFactory的序列化ID赋值
  2. getBeanFactory更简单,beanFactory的属性在构造方法中已经初始化为DefaultListableBeanFactory,所以这里返回的是DefaultListableBeanFactory;

还有,debug该方法,beanFactory中的bean信息只有几个,并不是将所有的bean信息都注册了,所以,beanFactory的自动发现(扫描bean信息)不是在这里发生了。

prepareBeanFactory方法

准备beanFactory,其实就是对beanFactory中的一些属性进行赋值;


    protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
      // Tell the internal bean factory to use the context's class loader etc.
      beanFactory.setBeanClassLoader(getClassLoader());// 设置类加载器
      beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));// 设置表达式解析器
      beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));// 设置property

      // Configure the bean factory with context callbacks.
        // 配置beanFactory上下文的回调处理
      beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
      beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
      beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
      beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
      beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
      beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
      beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);

      // BeanFactory interface not registered as resolvable type in a plain factory.
      // MessageSource registered (and found for autowiring) as a bean.
        // 添加自动发现及注入的支持
      beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
      beanFactory.registerResolvableDependency(ResourceLoader.class, this);
      beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
      beanFactory.registerResolvableDependency(ApplicationContext.class, this);

      // Register early post-processor for detecting inner beans as ApplicationListeners.
        // 监听器组件
      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)) {
         beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
      }
      if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
         beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
      }
   }

这个方法就比较复杂了,对beanFactory很多属性进行了设置。

最后

好了,beanFactory的预处理就差不多完成了,下面就是后置处理了。