• Spring 初始化流程


    开始

    在SpringIOC中,前面讲述了如何配置BeanDefinition和如何注册BeanDefinition,但是这些知识容器初始化的一部分,在AbstractApplicationContext中的refresh()方法中,可以看到整个初始化过程。

    今天就来看看这段曲折的初始化之路

    编写一个简单的启动类,打个断点到AbstractApplicationContext中的refresh()方法中。

    public class Application {
        public static void main(String[] args) {
    
            // setConfig -> call this.refresh()
            ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("context.xml");
        }
    }
    
    

    先看看refresh中调用了哪些方法:

    public void refresh() throws BeansException, IllegalStateException {
    		synchronized (this.startupShutdownMonitor) {
    			// Prepare this context for refreshing.
    			prepareRefresh();
    
    			// Tell the subclass to refresh the internal bean factory.
    			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
    
    			// Prepare the bean factory for use in this context.
    			prepareBeanFactory(beanFactory);
    
    			try {
    				// Allows post-processing of the bean factory in context subclasses.
    				postProcessBeanFactory(beanFactory);
    
    				// Invoke factory processors registered as beans in the context.
    				invokeBeanFactoryPostProcessors(beanFactory);
    
    				// Register bean processors that intercept bean creation.
    				registerBeanPostProcessors(beanFactory);
    
    				// Initialize message source for this context.
    				initMessageSource();
    
    				// Initialize event multicaster for this context.
    				initApplicationEventMulticaster();
    
    				// Initialize other special beans in specific context subclasses.
    				onRefresh();
    
    				// Check for listener beans and register them.
    				registerListeners();
    
    				// Instantiate all remaining (non-lazy-init) singletons.
    				finishBeanFactoryInitialization(beanFactory);
    
    				// Last step: publish corresponding event.
    				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()方法流程

    文中使用了ClassPathXmlApplicationContext作为容器

    1 prepareRefresh()

    protected void prepareRefresh() {
        	// 记录启动时间 然后设立对应的标志位
    		this.startupDate = System.currentTimeMillis();
    		this.closed.set(false);
    		this.active.set(true);
    
    		if (logger.isInfoEnabled()) {
    			logger.info("Refreshing " + this);
    		}
    
    		// 这是扩展方法,由子类去实现
    		initPropertySources();
    
    		// 创建Environment,验证必要的属性
    		getEnvironment().validateRequiredProperties();
    
    		// 初始化容器,用于装载早期的一些事件
    		this.earlyApplicationEvents = new LinkedHashSet<>();
    	}
    

    这里主要是做一些准备工作

    2 obtainFreshBeanFactory()

    protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
        // 这个方法是子类去实现的
        refreshBeanFactory();
        // 创建ApplicationContext内部持有的BeanFactory
        // getBeanFactory也是留给子类去实现,可以查看AbstractRefreshableApplicationContext和GernericApplicationContext
        ConfigurableListableBeanFactory beanFactory = getBeanFactory();
        if (logger.isDebugEnabled()) {
            logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
        }
        return beanFactory;
    }
    

    3 prepareBeanFactory(beanFactory)

    protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
    		// 设置beanFactory的classLoader为当前context的classLoader
    		beanFactory.setBeanClassLoader(getClassLoader());
    		// 设置EL表达式解析器(Bean初始化完成后填充属性时会用到)
    		// spring3增加了表达式语言的支持,默认可以使用#{bean.xxx}的形式来调用相关属性值
    		beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
    		// 设置属性注册解析器PropertyEditor 这个主要是对bean的属性等设置管理的一个工具
    		beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
    		
    		// 注册BeanPostProcessor-ApplicationContextAwareProcessor,从而在Aware接口实现类中的注入applicationContext等等
    		// 添加了一个处理aware相关接口的beanPostProcessor扩展,主要是使用beanPostProcessor的postProcessBeforeInitialization()前置处理方法实现aware相关接口的功能
    		// 类似的还有ResourceLoaderAware、ServletContextAware等等等等
    		beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
        
    		// 下面是忽略的自动装配
    		// 自动装配模式下,下面这些接口的实现类,都不会自动装配,自动装配不是@Autowired
            // 注意区分ignoreDependencyType,这个是在自动装配时忽略某个类型属性的依赖
    		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的类,就注册beanFactory
    		//  如果是ResourceLoader、ApplicationEventPublisher、ApplicationContext等等就注入当前对象this(applicationContext对象)
    		
    		// 此处registerResolvableDependency()方法注意:它会把他们加入到DefaultListableBeanFactory的resolvableDependencies字段里面缓存这,供后面处理依赖注入的时候使用 DefaultListableBeanFactory#resolveDependency处理依赖关系
    		// 这也是为什么我们可以通过依赖注入的方式,直接注入这几个对象比如ApplicationContext可以直接依赖注入
    		// 但是需要注意的是:这些Bean,Spring的IOC容器里其实是没有的。beanFactory.getBeanDefinitionNames()和beanFactory.getSingletonNames()都是找不到他们的,所以特别需要理解这一点
    		
    		beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
    		beanFactory.registerResolvableDependency(ResourceLoader.class, this);
    		beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
    		beanFactory.registerResolvableDependency(ApplicationContext.class, this);
    
    		// 在Bean初始化后检查是否实现了ApplicationListener接口
    		// 是则加入当前的applicationContext的applicationListeners列表 
    		beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
    
    
    		// 检查容器中是否包含名称为loadTimeWeaver的bean,实际上是增加Aspectj的支持
    		// AspectJ采用编译期织入、类加载期织入两种方式进行切面的织入
    		// 类加载期织入简称为LTW(Load Time Weaving),通过特殊的类加载器来代理JVM默认的类加载器实现
    		if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
    			// 添加BEAN后置处理器:LoadTimeWeaverAwareProcessor
            	// 在BEAN初始化之前检查BEAN是否实现了LoadTimeWeaverAware接口,
            	// 如果是,则进行加载时织入,即静态代理。
    			beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
    			// Set a temporary ClassLoader for type matching.
    			beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
    		}
    
    		// 注入一些其它信息的bean,比如environment、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());
    		}
    	}
    

    这里做的事情比较多,大多是和依赖的处理相关的配置。

    4 postProcessBeanFactory(beanFactory)

    这里是模板方法,留给子类去实现的逻辑,至此BeanFactory已经准备好

    5 invokeBeanFactoryPostProcessors(beanFactory)

    实例化并调用所有的BeanFactoryPostProcessor,当前必须是已经注册的

    protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
        // 调用BeanFactoryPostProcessor
       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)
        // 如果loadTimeWeaver这个Bean存在,那么就会配置上运行时织入的处理器LoadTimeWeaverAwareProcessor
       if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
          beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
          beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
       }
    }
    

    这里有个getBeanFactoryPostProcessors()方法,这个方法是获取AbstractApplicationContext内部的一个List类型属性,保存了手动添加的BeanPostProcessor实例。

    重点在PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors

    public static void invokeBeanFactoryPostProcessors(
    			ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {	
        // 先执行BeanDefinitionRegistryPostProcessors 
    	// 需要注意的是BeanDefinitionRegistryPostProcessors 为 BeanFactoryPostProcessor 的子接口 它新增了方法:void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry)
    	
    	// 所以BeanDefinitionRegistryPostProcessors,它可以我们介入,改变Bean的一些定义信息,或者动态注入Bean定义
    	Set<String> processedBeans = new HashSet<>();
    
    	// 只有此beanFactory 是BeanDefinitionRegistry  才能执行BeanDefinitionRegistryPostProcessor
    	if (beanFactory instanceof BeanDefinitionRegistry) {
    		BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
    
    		// 此处安放了两个容器,一个装载普通的BeanFactoryPostProcessor
    		// 另外一个装载和Bean定义有关的 BeanDefinitionRegistryPostProcessor
    		List<BeanFactoryPostProcessor> regularPostProcessors = new LinkedList<>();
    		List<BeanDefinitionRegistryPostProcessor> registryProcessors = new LinkedList<>();
    
    		// 这里是手动添加到ApplicationContext中的
    		for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
    			if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
    				BeanDefinitionRegistryPostProcessor registryProcessor =
    						(BeanDefinitionRegistryPostProcessor) postProcessor;
    				
    				// 这里执行post方法,然后然后吧它缓冲起来了,放在了registryProcessors里
    				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.
    		// 接下来,就是去执行Spring容器里面的一些PostProcessor了。
    		// 先执行实现了PriorityOrdered接口的,然后是Ordered接口的,最后执行剩下的
    		List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
    
    		
    	
    		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.
    		// 此处逻辑完全同上  处理实现Order接口的RegistryProcessors
    		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.
    		// 最后执行,两个排序接口都没有实现的BeanDefinitionRegistryPostProcessor们,并且也缓存起来
    		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();
    		}
    
    	
    		invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
    		invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
    	} else {
    		// Invoke factory processors registered with the context instance.
    		// 若是普通的Bean工厂,就直接执行set进来的后置处理器即可(因为容器里就没有其它Bean定义了)
    		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!
    	// 下面就是开始执行BeanFactoryPostProcessor 基本也是按照上面的顺序来执行的
    	// 执行使用配置注册的
    	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();
    }
    

    这里核心就是调用手动添加到ApplicationContext中的BeanFactoryPostProcessor和使用配置注册到BeanFactory的处理器。

    但是同时要处理两个问题:

    • BeanFactoryPostProcessor的顺序问题(实现了PriorityOrdered > 实现了Ordered > 什么都没实现)
    • 对于BeanDefinitionRegistryPostProcessor的处理,在这里面可以动态修改或者增加BeanDefinition

    6 registerBeanPostProcessors(beanFactory)

    注册BeanPostProcessor

    protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
       PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
    }
    

    重点戏还是在PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this)

    public static void registerBeanPostProcessors(
          ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
    
        // 从所与Bean定义中提取出BeanPostProcessor类型的Bean
       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.
        // BeanFactory中BeanPostProcessor的总数
       int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
        // 先注册一个BeanPostProcessorChecker
        // 这个有什么用呢,下面我会说明
       beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
    
       // Separate between BeanPostProcessors that implement PriorityOrdered,
       // Ordered, and the rest.
        // 先按优先级,归类了BeanPostProcessor
       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);
          }
       }
    
       // First, register the BeanPostProcessors that implement PriorityOrdered.
       sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
       registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
    
       // Next, register the BeanPostProcessors that implement 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);
    
       // Now, register all regular 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.
       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).
        // 把ApplicationListenerDetector 移动到最后
       beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
    }
    

    这里我们获取到了BeanFactory中定义的所有的BeanPostProcessor对象,并添加到AbstractBeanFactory中的List<BeanPostProcessor> beanPostProcessors中,以便后面创建bean的时候调用

    这里有一个BeanPostProcessorChecker,这里是为了检测创建Bean的时候是否所有的BeanPostProcessor都已经注册好。

    7 initMessageSource()

    这部分逻辑比较简单:向容器里注册一个一个事件源的单例Bean:MessageSource

    8 initApplicationEventMulticaster()

    初始化Spring的事件多播器:ApplicationEventMulticaster

    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);
    		} else {
    			this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
    			beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster); 
    		}
    	}
    

    检测用户是否自定义,没有就创建默认的

    9 onRefresh()

    一个模板方法,留给子类实现

    10 registerListeners()

    上面的过程已经注册好了事件多播器,现在注册监听器

    protected void registerListeners() {
    	
    		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...
    		// 如果存在早期应用事件,这里就直接发布了(同时就把earlyApplicationEvents该字段置为null)
    		Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
    		this.earlyApplicationEvents = null;
    		if (earlyEventsToProcess != null) {
    			for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
    				getApplicationEventMulticaster().multicastEvent(earlyEvent);
    			}
    		}
    	}
    

    11 finishBeanFactoryInitialization(beanFactory)

    实例化所有单例的非懒加载的Bean,并完成依赖注入,这里有点复杂

    protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
       // 初始化上下文的转换服务,ConversionService是一个类型转换接口
       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));
       }
    
       // 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);
       }
    
       // 停止使用临时的类加载器
       beanFactory.setTempClassLoader(null);
    
       // 缓存(冻结)所有的bean definition数据,不期望以后会改变
       beanFactory.freezeConfiguration();
    
       // 重要的方法  实例化所有剩余的单例Bean
       beanFactory.preInstantiateSingletons();
    }
    

    接下来就看这个重要的方法DefaultListableBeanFactory#preInstantiateSingletons

    public void preInstantiateSingletons() throws BeansException {
    		if (this.logger.isDebugEnabled()) {
    			this.logger.debug("Pre-instantiating singletons in " + this);
    		}
    
    		// 获取所有的beanName
    		List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
    
    		// 初始化所有的非懒加载的单例bean
    		for (String beanName : beanNames) {
    			RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
                // 不是抽象类, 是单例的,不是懒加载的
    			if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
                    // 如果是工厂Bean,那就会此工厂Bean放进去
    				if (isFactoryBean(beanName)) {
    					final FactoryBean<?> factory = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName);
    					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);
    				}
    			}
    		}
    
    		// 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();
    				}
    			}
    		}
    	}
    

    这里面通过FactoryBean定义的,它是懒加载的

    创建Bean-getBean(beanName)方法

    这里就是对于Bean的依赖的解析,完成Bean的创建,然后对Bean中的属性完成注入。

    由于这里内容较多,我们就放到下一次在总结。

    12 finishRefresh()

    protected void finishRefresh() {
       // Clear context-level resource caches (such as ASM metadata from scanning).
       clearResourceCaches();
    
       // 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);
    }
    

    refresh完成后的一些处理

    初始化声明周期方法,发布事件等等

  • 相关阅读:
    2020-2021-1 20201216 《信息安全专业导论》第十周学习总结
    2020-2021-1 20201216 《信息安全专业导论》第9周学习总结
    熟悉编程语言
    2020-2021-1 20201216 《信息安全专业导论》第八周学习总结
    如何学好编程
    2020-2021第一学期20202428《计算机科学概论》第二周自习总结
    “七剑下天山”学习小组第一周学习中遇到的问题及解决
    2020-2021第一学期20202407《计算机科学概论》第一次学习总结
    开启我的测试之路
    大数据测试
  • 原文地址:https://www.cnblogs.com/watertreestar/p/12732584.html
Copyright © 2020-2023  润新知