1. 程式人生 > 其它 >Spring原始碼 16 IOC refresh方法12

Spring原始碼 16 IOC refresh方法12

Spring IOC 的核心是 AbstractApplicationContextrefresh 方法。
其中一共有 13 個主要方法,這裡分析第 12 個:finishRefresh

1 AbstractApplicationContext

1-1 完成重新整理過程

finishRefresh()
protected void finishRefresh() {
   // 清除資源快取
   clearResourceCaches();
   // 初始化生命週期處理器
   initLifecycleProcessor();
   // 獲取生命週期處理器
   // 重新整理生命週期處理器
   getLifecycleProcessor().onRefresh();
   // 釋出事件
   publishEvent(new ContextRefreshedEvent(this));
   if (!NativeDetector.inNativeImage()) {
      LiveBeansView.registerApplicationContext(this);
   }
}

1-2 清除資源快取

clearResourceCaches()

2 DefaultResourceLoader

private final Map<Class<?>, Map<Resource, ?>> resourceCaches = new ConcurrentHashMap<>(4);

public void clearResourceCaches() {
   this.resourceCaches.clear();
}

1 AbstractApplicationContext

1-2 初始化生命週期處理器

initLifecycleProcessor()
protected void initLifecycleProcessor() {
   ConfigurableListableBeanFactory beanFactory = getBeanFactory();
   if (beanFactory.containsLocalBean(LIFECYCLE_PROCESSOR_BEAN_NAME)) {
      this.lifecycleProcessor = beanFactory.getBean(LIFECYCLE_PROCESSOR_BEAN_NAME, LifecycleProcessor.class);
      if (logger.isTraceEnabled()) {
         logger.trace("Using LifecycleProcessor [" + this.lifecycleProcessor + "]");
      }
   } else {
      DefaultLifecycleProcessor defaultProcessor = new DefaultLifecycleProcessor();
      defaultProcessor.setBeanFactory(beanFactory);
      this.lifecycleProcessor = defaultProcessor;
      beanFactory.registerSingleton(LIFECYCLE_PROCESSOR_BEAN_NAME, this.lifecycleProcessor);
      if (logger.isTraceEnabled()) {
         logger.trace("No '" + LIFECYCLE_PROCESSOR_BEAN_NAME + "' bean, using " + "[" + this.lifecycleProcessor.getClass().getSimpleName() + "]");
      }
   }
}

1-2 獲取生命週期處理器

getLifecycleProcessor()
private ResourcePatternResolver resourcePatternResolver;

LifecycleProcessor getLifecycleProcessor() throws IllegalStateException {
   if (this.lifecycleProcessor == null) {
      throw new IllegalStateException("LifecycleProcessor not initialized - " + "call 'refresh' before invoking lifecycle methods via the context: " + this);
   }
   return this.lifecycleProcessor;
}

if (this.lifecycleProcessor == null) 由於 this.lifecycleProcessor 在前面已經定義,這裡直接返回。

1-2 重新整理生命週期處理器

onRefresh()

3 DefaultLifecycleProcessor

public void onRefresh() {
   // 啟動 Beans
   startBeans(true);
   this.running = true;
}

3-1 啟動 Beans

startBeans(true)
private void startBeans(boolean autoStartupOnly) {
   // 獲取 Bean 生命週期 
   Map<String, Lifecycle> lifecycleBeans = getLifecycleBeans();
   Map<Integer, LifecycleGroup> phases = new TreeMap<>();

   lifecycleBeans.forEach((beanName, bean) -> {
      if (!autoStartupOnly || (bean instanceof SmartLifecycle && ((SmartLifecycle) bean).isAutoStartup())) {
         int phase = getPhase(bean);
         phases.computeIfAbsent(
               phase,
               p -> new LifecycleGroup(phase, this.timeoutPerShutdownPhase, lifecycleBeans, autoStartupOnly)
         ).add(beanName, bean);
      }
   });
   if (!phases.isEmpty()) {
      phases.values().forEach(LifecycleGroup::start);
   }
}

3-2 獲取 Bean 生命週期

getLifecycleBeans()
protected Map<String, Lifecycle> getLifecycleBeans() {
   // 獲取 Bean 工廠
   ConfigurableListableBeanFactory beanFactory = getBeanFactory();
   Map<String, Lifecycle> beans = new LinkedHashMap<>();
   String[] beanNames = beanFactory.getBeanNamesForType(Lifecycle.class, false, false);
   for (String beanName : beanNames) {
      String beanNameToRegister = BeanFactoryUtils.transformedBeanName(beanName);
      boolean isFactoryBean = beanFactory.isFactoryBean(beanNameToRegister);
      String beanNameToCheck = (isFactoryBean ? BeanFactory.FACTORY_BEAN_PREFIX + beanName : beanName);
      if ((beanFactory.containsSingleton(beanNameToRegister) && (!isFactoryBean || matchesBeanType(Lifecycle.class, beanNameToCheck, beanFactory))) || matchesBeanType(SmartLifecycle.class, beanNameToCheck, beanFactory)) {
         Object bean = beanFactory.getBean(beanNameToCheck);
         if (bean != this && bean instanceof Lifecycle) {
            beans.put(beanNameToRegister, (Lifecycle) bean);
         }
      }
   }
   return beans;
}

1 AbstractApplicationContext

1-2 釋出事件

publishEvent(new ContextRefreshedEvent(this))
public void publishEvent(ApplicationEvent event) {
   publishEvent(event, null);
}
protected void publishEvent(Object event, @Nullable ResolvableType eventType) {
   Assert.notNull(event, "Event must not be null");
   ApplicationEvent applicationEvent;
   if (event instanceof ApplicationEvent) {
      applicationEvent = (ApplicationEvent) event;
   } else {
      applicationEvent = new PayloadApplicationEvent<>(this, event);
      if (eventType == null) {
         eventType = ((PayloadApplicationEvent<?>) applicationEvent).getResolvableType();
      }
   }
   if (this.earlyApplicationEvents != null) {
      this.earlyApplicationEvents.add(applicationEvent);
   } else {
      // 獲取應用程式事件多播器
      // 多播事件
      getApplicationEventMulticaster().multicastEvent(applicationEvent, eventType);
   }
   if (this.parent != null) {
      if (this.parent instanceof AbstractApplicationContext) {
         ((AbstractApplicationContext) this.parent).publishEvent(event, eventType);
      } else {
         this.parent.publishEvent(event);
      }
   }
}