【SpringIOC容器初始化(一)】

编程

            // 初始化BeanFactory,进行xml文件读取
            ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

            // 对BeanFactory进行各种功能的填充
            prepareBeanFactory(beanFactory);

            try {
                // 子类覆盖方法做其他的处理
                postProcessBeanFactory(beanFactory);

                // 激活BeanFactory的处理器
                invokeBeanFactoryPostProcessors(beanFactory);

                // 注册拦截Bean创建的Bean处理器
                registerBeanPostProcessors(beanFactory);

                // 为上下文初始化Message源
                initMessageSource();

                // 初始化应用消息广播器
                initApplicationEventMulticaster();

                // 留给子类初始化其他的bean
                onRefresh();

                // 查找Listeners bean,注册到消息广播器中
                registerListeners();

                // 初始化剩下的单实例
                finishBeanFactoryInitialization(beanFactory);

                // 完成刷新过程,通知生命周期处理器
                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();
            }
        }
    }
    4.8 refresh中各个方法解析
    protected void prepareRefresh() {
       this.startupDate = System.currentTimeMillis();
       this.closed.set(false);
       this.active.set(true); 
       initPropertySources();  // 初始化配置文件
       getEnvironment().validateRequiredProperties();
       this.earlyApplicationEvents = new LinkedHashSet<ApplicationEvent>();
    }
    ..
    protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
       refreshBeanFactory();  // 这里对xml进行了解析,并且已经成功加入到map中了
       ConfigurableListableBeanFactory beanFactory = getBeanFactory();
       return beanFactory; // 最终返回这个bean,就是DefaultListableBeanFactory对象,加载了xml的工厂
    }
    ..
    子类实现:
  1、在bean工厂自动装配的时候忽略一些接口。如:ServletContextAware、ServletConfigAware
  2、注册WEB应用特定的域(scope)到bean工厂中,以便WebApplicationContext可以使用它们。比如"request", "session", "globalSession", "application",
  3、注册WEB应用特定的Environment bean到bean工厂中,以便WebApplicationContext可以使用它们。如:"contextParameters", "contextAttributes"
    protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
       PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());//主要是在这里面调用了所有的BeanFactoryPostProcessor
       if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
          beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
          beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
       }
    }
    protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
       PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
    }
    ..
    //初始化MessageSource接口的一个实现类。这个接口提供了消息处理功能。主要用于国际化/i18n。
    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());
             }
          }
       } 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); 
       }
    }
    ..
    //为这个context初始化一个事件广播器(ApplicationEventMulticaster)。
    protected void initApplicationEventMulticaster() {
       ConfigurableListableBeanFactory beanFactory = getBeanFactory();
       if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {//’applicationEventMulticaster’ 检查是否给context配了一个ApplicationEventMulticaster实现类
          this.applicationEventMulticaster =beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class); 
       }
       else {//如果没有,就是用默认的实现类 SimpleApplicationEventMulticaster
          this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
          beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster); 
       }
    }
    ..
    protected void onRefresh() throws BeansException {  // 子类实现.在AbstractApplicationContext的子类中初始化其他特殊的bean。其实就是初始化ThemeSource接口的实例。这个方法需要在所有单例bean初始化之前调用。
       // For subclasses: do nothing by default.
    }
    protected void registerListeners() {//注册应用的监听器。就是注册实现了ApplicationListener接口的监听器bean,这些监听器是注册到ApplicationEventMulticaster中的。这不会影响到其它监听器bean。在注册完以后,还会将其前期的事件发布给相匹配的监听器。
       // 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... 至此,已经完成将监听器注册到ApplicationEventMulticaster中,下面将发布前期的事件给监听器。
       Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
       this.earlyApplicationEvents = null;
       if (earlyEventsToProcess != null) {
          for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
             getApplicationEventMulticaster().multicastEvent(earlyEvent);
          }
       }
    }
    //完成bean工厂的初始化工作。这一步非常复杂,也非常重要,涉及到了bean的创建。第二步中只是完成了BeanDefinition的定义、解析、处理、注册。但是还没有初始化bean实例。这一步将初始化所有非懒加载的单例bean。这一步将会重新在一篇新的笔记中介绍。
    //对配置了lazy-init属性的Bean进行预实例化处理
    protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
       // Initialize conversion service for this context. 为容器指定一个转换服务(ConversionService)  在对某些Bean属性进行转换时使用  
       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(new StringValueResolver() {
             @Override
             public String resolveStringValue(String strVal) {
                return getEnvironment().resolvePlaceholders(strVal);
             }
          });
       }
       // Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
       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. /缓存容器中所有注册的BeanDefinition元数据,以防被修改
       beanFactory.freezeConfiguration();
       // Instantiate all remaining (non-lazy-init) singletons. //对配置了lazy-init属性的单态模式Bean进行预实例化处理
       beanFactory.preInstantiateSingletons();//DefaultListableBeanFactory对配置lazy-init属性的单例bean预实例化
    }
    ...
    //完成context的刷新。主要是调用LifecycleProcessor的onRefresh()方法,并且发布事件(ContextRefreshedEvent)
    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);
    }
    ...
    protected void resetCommonCaches() {
       ReflectionUtils.clearCache();
       ResolvableType.clearCache();
       CachedIntrospectionResults.clearClassLoader(getClassLoader());
    }

每天提高一点点

以上是 【SpringIOC容器初始化(一)】 的全部内容, 来源链接: utcz.com/z/514146.html

回到顶部