SpringIOC容器加载原理

1.AnnotationConfigApplicationContext(Config.class)

@Test
public void defaultConfigClassBeanNameIsGeneratedProperly() {
   ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
   Config configObject = (Config) context.getBean("annotationConfigApplicationContextTests.Config"
   assertNotNull(configObject);
}

如上实例代码所示。我们来看一下通过注解的方式。Spring是如何进行容器的初始化原理的。

SpringBeanFactory基础上提供了一些列具体容器的实现,其中AnnotationConfigApplicationContext是一个用来管理注解bean的容器,从AnnotationConfigApplicationContext的实现结构图中可以看出:

  • AnnotationConfigApplicationContext继承GenericApplicationContext这个通用应用上下文,GenericApplicationContext内部定义了一个DefaultListableBeanFactory实例,GenericApplicationContext实现了BeanDefinitionRegistry接口,所以可以通过AnnotationConfigApplicationContext实例注册bean defintion,然后调用refresh()方法来初始化上下文。
  • AnnotationConfigApplicationContext继承AbstractApplicationContextAbstractApplicationContext提供了ApplicationContext的抽象实现。

构造函数:

//1. 初始化bean读取器和扫描器;
    //调用父类GenericApplicationContext无参构造函数,初始化一个BeanFactory: DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory()
   this();
//2.注册bean配置类
   register(annotatedClasses);
//3.刷新上下文
   refresh();
}

1.1. this() 初始化bean读取器和扫描器

public AnnotationConfigApplicationContext() {
     //在IOC容器中初始化一个 注解bean读取器AnnotatedBeanDefinitionReader
    this.reader = new AnnotatedBeanDefinitionReader(this);
    //在IOC容器中初始化一个 按类路径扫描注解bean的 扫描器
this.scanner = new ClassPathBeanDefinitionScanner(this);

父类GenericApplicationContext部分代码:

public class GenericApplicationContext extends AbstractApplicationContext implements BeanDefinitionRegistry {
private final DefaultListableBeanFactory beanFactory;

//初始化一个BeanFactory
public GenericApplicationContext() {
      this.beanFactory = new DefaultListableBeanFactory();
    }
    …
}

1.2. register(annotatedClasses)

注册bean配置类, AnnotationConfigApplicationContext容器通过AnnotatedBean

DefinitionReaderregister方法实现注解bean的读取,具体源码如下:

 AnnotationConfigApplicationContext.javaregister方法

//按指定bean配置类读取bean

public void register(Class<?>... annotatedClasses) {
   for (Class<?> annotatedClass : annotatedClasses) {
      registerBean(annotatedClass);
   }
}

public void registerBean(Class<?> annotatedClass) {
   doRegisterBean(annotatedClass, null, null, null);
}

//核心实现逻辑
<T> void doRegisterBean(Class<T> annotatedClass, @Nullable Supplier<T> instanceSupplier, @Nullable String name,
      @Nullable Class<? extends Annotation>[] qualifiers, BeanDefinitionCustomizer... definitionCustomizers) {
    //将Bean配置类信息转成容器中AnnotatedGenericBeanDefinition数据结构, AnnotatedGenericBeanDefinition继承自BeanDefinition作用是定义一个bean的数据结构,下面的getMetadata可以获取到该bean上的注解信息
   AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(annotatedClass);
    //@Conditional装配条件判断是否需要跳过注册
   if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
      return;
   }
   //@param instanceSupplier a callback for creating an instance of the bean
   //设置回调
   abd.setInstanceSupplier(instanceSupplier);
   //解析bean作用域(单例或者原型),如果有@Scope注解,则解析@Scope,没有则默认为singleton
   ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);
  //作用域写回BeanDefinition数据结构, abd中缺损的情况下为空,将默认值singleton重新赋值到abd
   abd.setScope(scopeMetadata.getScopeName());
  //生成bean配置类beanName
   String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry));
   //通用注解解析到abd结构中,主要是处理Lazy, primary DependsOn, Role ,Description这五个注解
   AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);
  //@param qualifiers specific qualifier annotations to consider, if any, in addition to qualifiers at the bean class level
  // @Qualifier特殊限定符处理,
   if (qualifiers != null) {
      for (Class<? extends Annotation> qualifier : qualifiers) {
         if (Primary.class == qualifier) {
    // 如果配置@Primary注解,则设置当前Bean为自动装配autowire时首选bean
            abd.setPrimary(true);
         }
  else if (Lazy.class == qualifier) {
  //设置当前bean为延迟加载
            abd.setLazyInit(true);
         }
         else {
      //其他注解,则添加到abd结构中
            abd.addQualifier(new AutowireCandidateQualifier(qualifier));
         }
      }
   }
  //自定义bean注册,通常用在applicationContext创建后,手动向容器中一lambda表达式的方式注册bean,
  //比如:applicationContext.registerBean(UserService.class, () -> new UserService());
   for (BeanDefinitionCustomizer customizer : definitionCustomizers) {
     //自定义bean添加到BeanDefinition
      customizer.customize(abd);
   }
   //根据beanName和bean定义信息封装一个beanhold,heanhold其实就是一个 beanname和BeanDefinition的映射
   BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
  //创建代理对象
   definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
  // BeanDefinitionReaderUtils.registerBeanDefinition 内部通过DefaultListableBeanFactory.registerBeanDefinition(String beanName, BeanDefinition beanDefinition)按名称将bean定义信息注册到容器中,
  // 实际上DefaultListableBeanFactory内部维护一个Map<String, BeanDefinition>类型变量beanDefinitionMap,用于保存注bean定义信息(beanname 和 beandefine映射)
   BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
}

register方法重点完成了bean配置类本身的解析和注册,处理过程可以分为以下几个步骤:

  1. 根据bean配置类,使用BeanDefinition解析Bean的定义信息,主要是一些注解信息
  2. Bean作用域的处理,默认缺少@Scope注解,解析成单例
  3. 借助AnnotationConfigUtils工具类解析通用注解
  4. bean定义信息 Map <beanName,BeanDefinition的形式注册到ioc容器中

1.3. 容器refresh() 

refresh方法在AbstractApplicationContext容器中实现,refresh()方法的作用加载或者刷新当前的配置信息,如果已经存在spring容器,则先销毁之前的容器,重新创建spring容器,载入bean定义,完成容器初始化工作,debug进源码可以看出AnnotationConfigApplicationContext容器是通过调用其父类AbstractApplicationContextrefresh()函数启动整个IoC容器完成对Bean定义的载入。AbstractApplicationContext.javarefresh方法的实现代码如下:

public void refresh() throws BeansException, IllegalStateException {
   synchronized (this.startupShutdownMonitor) {
      //1.刷新上下文前的预处理
      prepareRefresh();
      //2.获取刷新后的内部Bean工厂
      ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
      //3.BeanFactory的预准备工作
      prepareBeanFactory(beanFactory);

      try {
         // BeanFactory准备工作完成后,可以做一些后置处理工作,
      // 4.空方法,用于在容器的子类中扩展
         postProcessBeanFactory(beanFactory);
         // 5. 执行BeanFactoryPostProcessor的方法,BeanFactory的后置处理器,在BeanFactory标准初始化之后执行的
         invokeBeanFactoryPostProcessors(beanFactory);
         // 6. 注册BeanPostProcessor(Bean的后置处理器),用于拦截bean创建过程
         registerBeanPostProcessors(beanFactory);
         // 7. 初始化MessageSource组件(做国际化功能;消息绑定,消息解析)
         initMessageSource();
         // 8. 初始化事件派发器
         initApplicationEventMulticaster();

         // 9.空方法,可以用于子类实现在容器刷新时自定义逻辑
         onRefresh();
         // 10. 注册时间监听器,将所有项目里面的ApplicationListener注册到容器中来
         registerListeners();
         // 11. 初始化所有剩下的单实例bean,单例bean在初始化容器时创建,原型bean在获取时(getbean)时创建
         finishBeanFactoryInitialization(beanFactory);
         // 12. 完成BeanFactory的初始化创建工作,IOC容器就创建完成;
         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();
      }
   }
}

具体分析refresh中的函数逻辑:

1.3.1.刷新上线文前的预处理 prepareRefresh()

AbstractApplicationContext. prepareRefresh ()方法:
protected void prepareRefresh() {
  //设置容器启动时间
   this.startupDate = System.currentTimeMillis();
  //启动标识
   this.closed.set(false);
   this.active.set(true);
   if (logger.isInfoEnabled()) {
      logger.info("Refreshing " + this);
   }

   //空方法,用于子容器自定义个性化的属性设置方法
   initPropertySources();
   //检验属性的合法等
   getEnvironment().validateRequiredProperties();
   //保存容器中的一些早期的事件
   this.earlyApplicationEvents = new LinkedHashSet<>();
}

1.3.2获取刷新后的内部Bean工厂,obtainFreshBeanFactory方法为内部bean工厂重新生成id,并返回bean工厂

AbstractApplicationContext. obtainFreshBeanFactory()方法

protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
  //为beanfactory生成唯一序列化id,beanfactory已经在GenericApplicationContext构造函数中初始化了,refreshBeanFactory的逻辑在AbstractApplicationContext的实现类GenericApplicationContext中
 refreshBeanFactory();
   //获取beanfactory
   ConfigurableListableBeanFactory beanFactory = getBeanFactory();
   if (logger.isDebugEnabled()) {
      logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
   }
   return beanFactory;
}

GenericApplicationContext.refreshBeanFactory()实现代码

protected final void refreshBeanFactory() throws IllegalStateException {
   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());
}

这里使用AbstractApplicationContext. refreshBeanFactory()在不同实现容器中有点区别,如果是以xml方式配置bean,会使用AbstractRefreshableApplicationContext容器中的实现,该容器中实现xml配置文件定位,并通过BeanDefinition载入和解析xml配置文件。而如果是注解的方式,则并没有解析项目包下的注解,而是通过在refresh()方法中执行ConfigurationClassPostProcessor后置处理器完成对bean的加载.

1.3.3.BeanFactory的预准备工作 prepareBeanFactory(beanFactory)

 prepareBeanFactory主要完成beanFactory的一些属性设置

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

   // Configure the bean factory with context callbacks.
   beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));  //添加一个BeanPostProcessor实现ApplicationContextAwareProcessor
//设置忽略的自动装配接口,表示这些接口的实现类不允许通过接口自动注入
   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));

   //添加编译时的AspectJ
   if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
      beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
      // Set a temporary ClassLoader for type matching.
      beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
   }

   // 给beanfactory容器中注册组件ConfigurableEnvironment、systemProperties、systemEnvironment
   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());
   }
}

  这一步有两个需要关注的点,在 prepareBeanFactory 的时候,往容器中注册了两个比较重要的后置处理器分别是

beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
  • ApplicationContextAwareProcessor.class

这两个后置处理器是spring默认注入进去的,那么这两个后置处理器到底有什么用呢?我们先来看一下 new ApplicationContextAwareProcessor(this) 这个后置处理器.



	@Override
	@Nullable
	public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {
		AccessControlContext acc = null;

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

如上代码片段可以看到  ApplicationContextAwareProcessor 这个后置处理器主要是在对象初始化前给实现了各种xxxAware接口的类注入对应的Aware,其中我们在写代码过程中用的比较多的就有

ApplicationContextAware 就是通过工厂准备阶段注入的这个后置处理器实现的.

  • ApplicationListenerDetector.class

 可以看到ApplicationListenerDetector实际上也是一个bean的后置处理器.

@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) {
		if (bean instanceof ApplicationListener) {
			// potentially not detected as a listener by getBeanNamesForType retrieval
			Boolean flag = this.singletonNames.get(beanName);
			if (Boolean.TRUE.equals(flag)) {
				// singleton bean (top-level or inner): register on the fly
				this.applicationContext.addApplicationListener((ApplicationListener<?>) bean);
			}
			else if (Boolean.FALSE.equals(flag)) {
				if (logger.isWarnEnabled() && !this.applicationContext.containsBean(beanName)) {
					// inner bean with other scope - can't reliably process events
					logger.warn("Inner bean '" + beanName + "' implements ApplicationListener interface " +
							"but is not reachable for event multicasting by its containing ApplicationContext " +
							"because it does not have singleton scope. Only top-level listener beans are allowed " +
							"to be of non-singleton scope.");
				}
				this.singletonNames.remove(beanName);
			}
		}
		return bean;
	}

ApplicationListenerDetector主要就是把实现了 ApplicationListener接口的监听收集到多播器里面.方便后期统一对时间监听器做事件分发.

1.3.4 postProcessBeanFactory(beanFactory);

// Allows post-processing of the bean factory in context subclasses.

这一步什么也没做主要是给 AbstractApplicationContext 这个的子类预留了一个对beanFactory进行增强的接口

1.3.5.执行bean工厂的后置处理器 invokeBeanFactoryPostProcessors(beanFactory)

   IOC容器初始化过程中有三个重要的步骤,

          1:资源定位,2bean定义的载入,3:将bean名称、bean定义以key-value形式注册到容器,这三个步骤都将在此完成。

 AbstractApplicationContext. 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()));
   }
}

invokeBeanFactoryPostProcessorsbeanFactory getBeanFactoryPostProcessors())方法内部执行实现了BeanFactoryPostProcessor BeanDefinitionRegistryPostProcessor这两个接口的Processor.

1 先获取所有BeanDefinitionRegistryPostProcessor的实现,按优先级执行(是否实现PriorityOrdered优先级接口,是否实现Ordered顺序接口);

2 再以相同的策略执行所有BeanFactoryPostProcessor的实现。PostProcessorRegistrationDelegate. invokeBeanFactoryPostProcessors实现:

这里使用这两个BeanFactoryPostProcessor的目的主要是为了对spring的容器管理器,也就是我们的BeanFactory做增强处理,比如放入我们自定一的beanDefinition或者修改beanFactory的属性值的. 

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;
      List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
      List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();

      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<BeanDefinitionRegistryPostProcessor> 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<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
   List<String> orderedPostProcessorNames = new ArrayList<>();
   List<String> nonOrderedPostProcessorNames = new ArrayList<>();
   for (String ppName : postProcessorNames) {
      if (processedBeans.contains(ppName)) {
         // skip - already processed in first phase above
      }
      else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
         priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
      }
      else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
         orderedPostProcessorNames.add(ppName);
      }
      else {
         nonOrderedPostProcessorNames.add(ppName);
      }
   }

   // First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
   sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
   invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

   // Next, invoke the BeanFactoryPostProcessors that implement Ordered.
   List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>();
   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();
}

这里面在处理BeanDefinitionRegistryPostProcessors时有一个非常重要的过程,AnnotationConfigApplicationContext构造函数在初始化reader时为内部beanFactory容器初始化了一个idorg.springframework.context.annotation.internal.ConfigurationAnnotationProcessor的组件,这是一个ConfigurationClassPostProcessor组件,用来处理添加@Configuration注解的类,并将Bean定义注册到BeanFactory中。invokeBeanFactoryPostProcessors的实现过程是较复杂,

 ConfigurationClassPostProcessor.class 核心方法

public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
		List<BeanDefinitionHolder> configCandidates = new ArrayList<>();
		String[] candidateNames = registry.getBeanDefinitionNames();

        1 //收集所有 @Configuration.class @Component.class @ComponentScan.class
          //@Import.class @ImportResource @Bean 标注的类
		for (String beanName : candidateNames) {
			BeanDefinition beanDef = registry.getBeanDefinition(beanName);
			if (ConfigurationClassUtils.isFullConfigurationClass(beanDef) ||
					ConfigurationClassUtils.isLiteConfigurationClass(beanDef)) {
				if (logger.isDebugEnabled()) {
					logger.debug("Bean definition has already been processed as a configuration class: " + beanDef);
				}
			}
			else if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {
				configCandidates.add(new BeanDefinitionHolder(beanDef, beanName));
			}
		}

		// @Configuration如果没有这些注解标注的类就返回
		if (configCandidates.isEmpty()) {
			return;
		}

		// 对这些类进行排序
		configCandidates.sort((bd1, bd2) -> {
			int i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition());
			int i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition());
			return Integer.compare(i1, i2);
		});

		// Detect any custom bean name generation strategy supplied through the enclosing application context
		SingletonBeanRegistry sbr = null;
		if (registry instanceof SingletonBeanRegistry) {
			sbr = (SingletonBeanRegistry) registry;
			if (!this.localBeanNameGeneratorSet) {
				BeanNameGenerator generator = (BeanNameGenerator) sbr.getSingleton(CONFIGURATION_BEAN_NAME_GENERATOR);
				if (generator != null) {
					this.componentScanBeanNameGenerator = generator;
					this.importBeanNameGenerator = generator;
				}
			}
		}

		if (this.environment == null) {
			this.environment = new StandardEnvironment();
		}

		// 解析配置类注解配置类
		ConfigurationClassParser parser = new ConfigurationClassParser(
				this.metadataReaderFactory, this.problemReporter, this.environment,
				this.resourceLoader, this.componentScanBeanNameGenerator, registry);

		Set<BeanDefinitionHolder> candidates = new LinkedHashSet<>(configCandidates);
		Set<ConfigurationClass> alreadyParsed = new HashSet<>(configCandidates.size());
		do {
			parser.parse(candidates); //具体解析过程
			parser.validate();

			Set<ConfigurationClass> configClasses = new LinkedHashSet<>(parser.getConfigurationClasses());//解析以后对注解的进行收集

			configClasses.removeAll(alreadyParsed);

			// Read the model and create bean definitions based on its content
			if (this.reader == null) {
				this.reader = new ConfigurationClassBeanDefinitionReader(
						registry, this.sourceExtractor, this.resourceLoader, this.environment,
						this.importBeanNameGenerator, parser.getImportRegistry());
			}
			this.reader.loadBeanDefinitions(configClasses);//加载bean
			alreadyParsed.addAll(configClasses);

			candidates.clear();
			if (registry.getBeanDefinitionCount() > candidateNames.length) {
				String[] newCandidateNames = registry.getBeanDefinitionNames();
				Set<String> oldCandidateNames = new HashSet<>(Arrays.asList(candidateNames));
				Set<String> alreadyParsedClasses = new HashSet<>();
				for (ConfigurationClass configurationClass : alreadyParsed) {
					alreadyParsedClasses.add(configurationClass.getMetadata().getClassName());
				}
				for (String candidateName : newCandidateNames) {
					if (!oldCandidateNames.contains(candidateName)) {
						BeanDefinition bd = registry.getBeanDefinition(candidateName);
						if (ConfigurationClassUtils.checkConfigurationClassCandidate(bd, this.metadataReaderFactory) &&
								!alreadyParsedClasses.contains(bd.getBeanClassName())) {
							candidates.add(new BeanDefinitionHolder(bd, candidateName));
						}
					}
				}
				candidateNames = newCandidateNames;
			}
		}
		while (!candidates.isEmpty());

		// Register the ImportRegistry as a bean in order to support ImportAware @Configuration classes
		if (sbr != null && !sbr.containsSingleton(IMPORT_REGISTRY_BEAN_NAME)) {
			sbr.registerSingleton(IMPORT_REGISTRY_BEAN_NAME, parser.getImportRegistry());
		}

		if (this.metadataReaderFactory instanceof CachingMetadataReaderFactory) {
			// Clear cache in externally provided MetadataReaderFactory; this is a no-op
			// for a shared cache since it'll be cleared by the ApplicationContext.
			((CachingMetadataReaderFactory) this.metadataReaderFactory).clearCache();
		}
	}

  如上代码所示不管是@bean @Import @ImportedResources或者 ImportBeanDefinitionRegistrar 接口实现的bean定义,最终都会被当道容器中

this.registry.registerBeanDefinition(beanName, beanDefToRegister);

 综上:也就是说 ConfigurationClassPostProcessor这个类是一个BeanFactoryPostProcessor的容器增强子类.这个类主要做的事情就是解析所有注解能生成的bean.最后把这些bean放到容器中.

1.3.6.注册BeanPostProcessor(Bean的后置处理器),用于拦截bean创建过程
 

 注册后置处理器的大致逻辑是:

  1.获取所有的 BeanPostProcessor

  2.根据处理器实现的接口区分出4中类型:

    a.实现PriorityOrdered接口的处理器

    b.实现Ordered接口的处理器,

    c.实现MergedBeanDefinitionPostProcessor接口的处理器,

    d.普通后置处理器

  3.按这个4中类型依次注册到容器中

  4.注册一个特殊的后置处理器ApplicationListenerDetectorApplicationListenerDetector本身也实现了MergedBeanDefinitionPostProcessor接口,有个问题,这个为什么没有在上面c,d之间注册,而是放到最后?

AbstractApplicationContext .registerBeanPostProcessors(beanFactory);实现逻辑:

protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
   PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
 }
 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);
       }
    }
 
    //先注册实现PriorityOrdered接口的处理器,添加到beanfactory容器中beanFactory.addBeanPostProcessor(postProcessor);
    sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
    registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
 
    //注册实现Ordered接口的处理器
    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);
 
    // 注册没有实现Ordered或PriorityOrdered的处理器(nonOrderedPostProcessors)
   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.
   //最后,重新注册所有internal BeanPostProcessors(实现MergedBeanDefinitionPostProcessor接口的后置处理器
    sortPostProcessors(internalPostProcessors, beanFactory);
    registerBeanPostProcessors(beanFactory, internalPostProcessors);
 
    //注册ApplicationListenerDetector,用于Bean创建完时检查是否是ApplicationListener
    beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
 }

这里有一些比较重要的后置处理器,AbstractAutoProxyCreator aop相关的后置处理器,AutowiredAnnotationBeanPostProcessor @autoware自动装配的后置处理器,ApplicationListenerDetector 获取注册监听器的后置处理器. ApplicationContextAwareProcessor  通过Aware接口注册对象的后置处理器等等.这些后置处理器都还是比较重要.

1.3.7.初始化MessageSource组件(做国际化功能;消息绑定,消息解析)

 AbstractApplicationContext .initMessageSource()方法实现代码:

protected void initMessageSource() {
//获取beanFactory
   ConfigurableListableBeanFactory beanFactory = getBeanFactory();
//判断是否已经存在id为MESSAGE_SOURCE_BEAN_NAME的组件
   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.isDebugEnabled()) {
         logger.debug("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.isDebugEnabled()) {
         logger.debug("Unable to locate MessageSource with name '" + MESSAGE_SOURCE_BEAN_NAME +
               "': using default [" + this.messageSource + "]");
      }
   }
}

1.3.8.初始化事件派发器

 AbstractApplicationContext .initApplicationEventMulticaster()方法实现逻辑

protected void initApplicationEventMulticaster() {
//获取BeanFactory
   ConfigurableListableBeanFactory beanFactory = getBeanFactory();
//如果有配置beanName为applicationEventMulticaster的事件派发器,则将其赋给容器中的applicationEventMulticaster对象
   if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
      this.applicationEventMulticaster =
            beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
      if (logger.isDebugEnabled()) {
         logger.debug("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
      }
   }
   else {
//不存在,则创建一个SimpleApplicationEventMulticaster事件派发器,并注册到beanfactory中
      this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
      beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
      if (logger.isDebugEnabled()) {
         logger.debug("Unable to locate ApplicationEventMulticaster with name '" +
               APPLICATION_EVENT_MULTICASTER_BEAN_NAME +
               "': using default [" + this.applicationEventMulticaster + "]");
      }
   }
}

1.3.9 onRefresh();

// Initialize other special beans in specific context subclasses.

AbstractApplicationContext 这个方法交给子类初始化特定的子类的

1.3.10. 注册时间监听器,将ApplicationListener注册到容器中来

 registerListeners方法主要实现将事件监听器添加到IOC容器中的事件派发器中,并在最后做了一个事件发布的逻辑(如果之前的步骤有产生事件,则将earlyApplicationEvents中保存的事件逐一发布)

AbstractApplicationContext .registerListeners()方法实现逻辑:

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 (earlyEventsToProcess != null) {
      for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
         getApplicationEventMulticaster().multicastEvent(earlyEvent);
      }
   }
}

1.3.11. 初始化所有剩下的单实例bean,单例bean在初始化容器时创建,原型bean在获取时(getbean)时创建

 AbstractApplicationContext.finishBeanFactoryInitialization(beanFactory);方法实现代码:

protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
   //组件转换器相关
   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));
   }
   //aspectj相关.
   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();
   // 初始化后剩下的单实例bean
   beanFactory.preInstantiateSingletons();
}

DefaultListableBeanFactory. preInstantiateSingletons()方法实现逻辑:

public void preInstantiateSingletons() throws BeansException {
   if (logger.isDebugEnabled()) {
      logger.debug("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.
  //容器中所有bean名称
   List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);

   // Trigger initialization of all non-lazy singleton beans...
   for (String beanName : beanNames) {
  //获取Bean的定义信息;RootBeanDefinition
      RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
  //非抽象,单例,非延迟加载
      if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
  //是否是FactoryBean
         if (isFactoryBean(beanName)) {
    // 通过"&beanName"获取工厂Bean实例
            Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
            if (bean instanceof FactoryBean) {
               final 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 {
      //不是FactoryBean,则利用getBean(beanName)实例化bean
            getBean(beanName);
         }
      }
   }

   // Trigger post-initialization callback for all applicable beans...
   for (String beanName : beanNames) {
      Object singletonInstance = getSingleton(beanName);
      if (singletonInstance instanceof SmartInitializingSingleton) {
         final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
         if (System.getSecurityManager() != null) {
            AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
               smartSingleton.afterSingletonsInstantiated();
               return null;
            }, getAccessControlContext());
         }
         else {
            smartSingleton.afterSingletonsInstantiated();
         }
      }
   }
}

 如上所示  List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);如上代码所示遍历所有的单实例Beandefinition的缓存池.对所有的bean 创建实例.并且放入容器池.最后在所有的bean实例化完成以后调用 SmartInitializingSingleton的afterSingletonsInstantiated对所有实例初始化完做一个后置处理.至于这里单实例创建的过程我将会重新启动一遍博客来讲解bean的实例化过程.其实在spring中所有bean的创建过程都依赖于getBean()这个方法的递归创建.
​​​​​​​

1.3.12. 完成BeanFactory的初始化创建工作,IOC容器就创建完成

 AbstractApplicationContext.finishRefresh()实现逻辑:

protected void finishRefresh() {
   // Clear context-level resource caches (such as ASM metadata from scanning).
   clearResourceCaches();
   //初始化和生命周期有关的后置处理器LifecycleProcessor,默认DefaultLifecycleProcessor
   initLifecycleProcessor();
   // 回调生命周期处理器
   getLifecycleProcessor().onRefresh();
   //发布容器刷新完成事件:ContextRefreshedEvent
   publishEvent(new ContextRefreshedEvent(this));
   LiveBeansView.registerApplicationContext(this);
}

以上基本分析了AnnotationConfigApplicationContext容器的初始化过程, Spring容器在启动过程中,会先保存所有注册进来的Bean的定义信息;Spring容器根据条件创建Bean实例,区分单例,还是原型,后置处理器等(后置处理器会在容器创建过程中通过getBean创建,并执行相应的逻辑);Spring容器在创建bean实例后,会使用多种后置处理器来增加bean的功能,比如处理自动注入,AOP,异步,这种后置处理器机制也丰富了bean的功能。

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐