Spring 容器初始化之Bean的後置處理器

你的點贊是我最大動力,期待與你的共同進步web

本文主要涉及:Spring中Bean的後置處理加入容器過程。spring

6.registerBeanPostProcessors

protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
 PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this); } 複製代碼

  在Spring中對於 BeanPostProcessor 的處理分爲兩個過程,對於內置的 BeanPostProcessor的子類的實現,添加到 IoC容器中,是經過refresh() 方法中的 prepareBeanFactory() 過程來完成的。好比 ApplicationContextAwareProcessorApplicationListenerDetector。對於 ImportAwareBeanPostProcessor 是在,處理 ConfigurationClassPostProcessor時,對 @Configuration註解的類生成CGLIB 代理的時候加入容器中的。最後,在Spring中對於 BeanPostProcessor的實現類的處理,是在 refresh() 方法中有一個步驟 registerBeanPostProcessors() 來完成註冊的,如 BeanPostProcessorCheckerCommonAnnotationBeanPostProcessor 以及 AutowiredAnnotationBeanPostProcessorCommonAnnotationBeanPostProcessor。這樣,在容器初始化之處,沒有本身實現 BeanPsotProcessor 的時候,容器中就包含了6個Bean的後置處理器的實現。其中對於 registerBeanPostProcessors() 方法的詳細代碼實現,下面一一分析:app

public static void registerBeanPostProcessors(  ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {   // 獲取BeanDefinitionMap中全部的BeanPostProcessor  String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);   /**  * BeanPostProcessorChecker 是一個普通的信息打印,可能會有些狀況  * 當spring 的配置中的後置處理器尚未被註冊就已經開始了bean的初始化時  * 便會打印出 BeanPostProcessorChecker 中設定的值  */  int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;  // new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount)  // 建立一個 默認的 PostProcessorRegistrationDelegate, BeanPostProcessorChecker 是 PostProcessorRegistrationDelegate  // 中的一個靜態的內部類 且實現了 BeanPostProcessor 接口  beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));   /**  * 使用priorityOrdered 保證順序  */  List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();  List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();  /**  * 使用 ordered 保證順序  */  List<String> orderedPostProcessorNames = new ArrayList<>();  /**  * 無序 BeanPostProcessor  */  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 的 BeanPostProcessors  */  sortPostProcessors(priorityOrderedPostProcessors, beanFactory);  registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);   /**  * 第二步,註冊全部實現 Ordered 的 BeanPostProcessors  */  List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>();  for (String ppName : orderedPostProcessorNames) {  BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);  orderedPostProcessors.add(pp);  if (pp instanceof MergedBeanDefinitionPostProcessor) {  internalPostProcessors.add(pp);  }  }  sortPostProcessors(orderedPostProcessors, beanFactory);  registerBeanPostProcessors(beanFactory, orderedPostProcessors);   /**  * 第三步,註冊無序 的 BeanPostProcessors  */  List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>();  for (String ppName : nonOrderedPostProcessorNames) {  BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);  nonOrderedPostProcessors.add(pp);  if (pp instanceof MergedBeanDefinitionPostProcessor) {  internalPostProcessors.add(pp);  }  }  registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);   // Finally, re-register all internal BeanPostProcessors.  /**  * 註冊全部 MergedBeanDefinitionPostProcessor 類型的 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)); } 複製代碼

將Bean的後置處理器加入到容器中

public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
 Assert.notNull(beanPostProcessor, "BeanPostProcessor must not be null");  // Remove from old position, if any  this.beanPostProcessors.remove(beanPostProcessor);  // Track whether it is instantiation/destruction aware  if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) {  this.hasInstantiationAwareBeanPostProcessors = true;  }  if (beanPostProcessor instanceof DestructionAwareBeanPostProcessor) {  this.hasDestructionAwareBeanPostProcessors = true;  }  // Add to end of list  this.beanPostProcessors.add(beanPostProcessor); } 複製代碼

  至此,Spring 中容器初始化不部分的解析已經處理完了,到目前爲止,容器的中的東西基本上已經齊活了,經過下面的容器造成圖示例: 編輯器

7.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 + "]");  }  } } 複製代碼

  判斷beanFactory中是否有名字爲messageSource的bean,若是有,從beanFactory中獲取而且判斷獲取的是否是HierarchicalMessageSource類型的,若是是設置其父級消息源 若是沒有,新建DelegatingMessageSource類做爲messageSource的Bean。post

8.initApplicationEventMulticaster()

protected void initApplicationEventMulticaster() {
 ConfigurableListableBeanFactory beanFactory = getBeanFactory();  if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {  this.applicationEventMulticaster =  beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);  if (logger.isTraceEnabled()) {  logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");  }  }  else {  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() + "]");  }  } } 複製代碼

  初始化 ApplicationEventMulticaster 若是用戶自定義了事件廣播器,那麼使用用戶自定義的事件廣播器若是用戶沒有自定義事件廣播器,那麼使用默認的 ApplicationEventMulticasterSimpleApplicationEventMulticaster.學習

9.onRefresh()

protected void onRefresh() throws BeansException {
 // For subclasses: do nothing by default. } 複製代碼

  空方法,Spring 預留給子類須要時來實現。this

10.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);  }  } } 複製代碼

  獲取容器中的監聽器,而後獲得當前容器中的 applicationEventMulticaster,調用 addApplicationListener進行添加。 這裏的 applicationEventMulticaster 就是剛纔初始化的,若是爲空就是 SimpleApplicationEventMulticaster編碼

  從BeanFactory中獲取ApplicationListener類型的Bean,而且添加爲ListenerBeans。url

  獲取須要提早發佈的事件,進行廣播。spa

最後

  至此, refresh()方法中的各個子方法的學習,僅剩了一個finishBeanFactoryInitialization()。關於這個方法,涉及到不少新的過程 而且與 Bean 的實例化過程息息相關。後面的文章將會介紹 Bean 的實例化。這裏就是Bean的實例化入口的地方。

本文使用 mdnice 排版

相關文章
相關標籤/搜索