Spring容器初始化(3)

版权声明: https://blog.csdn.net/ph3636/article/details/80917829

接上篇Spring容器初始化(2),初始化bean,开始执行一些额外的实现接口BeanNameAware,BeanClassLoaderAware,BeanFactoryAware

protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
   if (System.getSecurityManager() != null) {
      AccessController.doPrivileged(new PrivilegedAction<Object>() {
         @Override
         public Object run() {
            invokeAwareMethods(beanName, bean);
            return null;
         }
      }, getAccessControlContext());
   }
   else {
      invokeAwareMethods(beanName, bean);
   }

   Object wrappedBean = bean;
   if (mbd == null || !mbd.isSynthetic()) {
      wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
   }

   try {
      invokeInitMethods(beanName, wrappedBean, mbd);
   }
   catch (Throwable ex) {
      throw new BeanCreationException(
            (mbd != null ? mbd.getResourceDescription() : null),
            beanName, "Invocation of init method failed", ex);
   }
   if (mbd == null || !mbd.isSynthetic()) {
      wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
   }
   return wrappedBean;
}

从容器中找出所有的初始化前置处理器,依次执行。在真正的初始化操作之前可以对实例进行一些更改。

public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
      throws BeansException {

   Object result = existingBean;
   for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
      result = beanProcessor.postProcessBeforeInitialization(result, beanName);
      if (result == null) {
         return result;
      }
   }
   return result;
}

执行初始化方法,首先判断是否实现了InitializingBean接口,也就是执行常见的afterPropertiesSet方法。

protected void invokeInitMethods(String beanName, final Object bean, RootBeanDefinition mbd)
      throws Throwable {

   boolean isInitializingBean = (bean instanceof InitializingBean);
   if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
      if (logger.isDebugEnabled()) {
         logger.debug("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
      }
      if (System.getSecurityManager() != null) {
         try {
            AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
               @Override
               public Object run() throws Exception {
                  ((InitializingBean) bean).afterPropertiesSet();
                  return null;
               }
            }, getAccessControlContext());
         }
         catch (PrivilegedActionException pae) {
            throw pae.getException();
         }
      }
      else {
         ((InitializingBean) bean).afterPropertiesSet();
      }
   }

   if (mbd != null) {
      String initMethodName = mbd.getInitMethodName();
      if (initMethodName != null && !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
            !mbd.isExternallyManagedInitMethod(initMethodName)) {
         invokeCustomInitMethod(beanName, bean, mbd);
      }
   }
}
然后通过反射操作执行"init-method"标签定的初始化方法。

ReflectionUtils.makeAccessible(initMethod);
initMethod.invoke(bean);

执行初始化后置处理applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);

注册容器销毁时bean相应的处理事件,当然这个实例必须要实现DisposableBean接口或者配置有"destroy-method"标签才行

registerDisposableBeanIfNecessary(beanName, bean, mbd);
把初始化后的实例放进容器缓存中,移除一些临时的缓存

protected void addSingleton(String beanName, Object singletonObject) {
   synchronized (this.singletonObjects) {
      this.singletonObjects.put(beanName, (singletonObject != null ? singletonObject : NULL_OBJECT));
      this.singletonFactories.remove(beanName);
      this.earlySingletonObjects.remove(beanName);
      this.registeredSingletons.add(beanName);
   }
}

如果该实例是FactoryBean类型,再执行特有的方法getObject()来取出真正的初始化类实例

bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
最后当实例实现了SmartInitializingSingleton接口的话会再执行afterSingletonsInstantiated方法,至此,实例初始化完毕。

12. 完成容器启动,发布一些事件,开启生命周期

// Last step: publish corresponding event.
finishRefresh();
protected void finishRefresh() {
   // Initialize lifecycle processor for this context.
   initLifecycleProcessor();

   // Propagate refresh to lifecycle processor first.
   getLifecycleProcessor().onRefresh();

   // Publish the final event.
   publishEvent(new ContextRefreshedEvent(this));

   // Participate in LiveBeansView MBean, if active.
   LiveBeansView.registerApplicationContext(this);
}

设置或创建默认的生命周期执行类DefaultLifecycleProcessor,启动拥有生命周期的对象。

向上下文事件多播器中发布上下文创建成功事件,监听器依次执行listener.onApplicationEvent(event);dubbo的ServiceBean就监听了这个事件,然后暴露服务,还有就是SpringMVC的DispatcherServlet的父类也间接的监听了该事件,从来启动web容器,实现MVC的主要功能。同样的事件也同步给父容器。

getApplicationEventMulticaster().multicastEvent(applicationEvent, eventType);

最后如果需要的话,注册JMX扩展

// Participate in LiveBeansView MBean, if active.
LiveBeansView.registerApplicationContext(this);

猜你喜欢

转载自blog.csdn.net/ph3636/article/details/80917829