spring bean 生命周期 3 (spring5.0版本)

spring生命周期2
上一篇spring bean 生命周期2主要分析了register(componentClasses)方法;

	public AnnotationConfigApplicationContext(Class<?>... componentClasses) {
     
		this();
		register(componentClasses);
		refresh();
	}

本主要讲如上的refresh()方法invokeBeanFactoryPostProcessors(beanFactory)

跟踪refresh()方法:invokeBeanFactoryPostProcessors(beanFactory)这个方法之前的
注释都写在方法上了.

	@Override
	public void refresh() throws BeansException, IllegalStateException {
     
		synchronized (this.startupShutdownMonitor) {
     
			//这里不是重点,初始化的准备
			prepareRefresh();

			//这里的beanfactory就是之前的beanfactory,本文包含的bdmap中有6个bdmap
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

			// 准备参数,在这个方法里会加上一个BeanPostProcessor的子类型ApplicationContextAwareProcessor
			prepareBeanFactory(beanFactory);

			try {
     
				// 里面是空方法,spring预留的
				postProcessBeanFactory(beanFactory);

				// 
				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();
			}
		}
	}

跟踪invokeBeanFactoryPostProcessors(beanFactory)方法:

	protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
     
		PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());

		 //检查容器中是否包含名称为loadTimeWeaver的bean,实际上是增加Aspectj的支持
		// AspectJ采用编译期织入、类加载期织入两种方式进行切面的织入
		// 类加载期织入简称为LTW(Load Time Weaving),通过特殊的类加载器来代理JVM默认的类
		//加载器实现,本文未加入AspectJ的支持;
		if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
     
			beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
			beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
		}
	}
	

跟踪
PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());注释写在方法上了.

	public static void invokeBeanFactoryPostProcessors(
			ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
     

		// 存储任何的处理过的beanname.
		Set<String> processedBeans = new HashSet<>();

		if (beanFactory instanceof BeanDefinitionRegistry) {
     
			BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
			//这个是bean工厂后置处理器的顶级接口,简称bfpp,
			List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
			
			//这个是bean工厂后置处理器的二级接口它继承了顶级接口,简称bdrpp,
			List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
			
			//这里的beanFactoryPostProcessors值为空的,这里的值
			//是applicationContext的成员变量beanFactoryPostProcessors
			//如果业务想要增加的话,我们可以在调用refresh()方法之前进行手动加入
			//举个例子:
			//AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext();
			//ac.register(Appconfig.class);
			//ac.addBeanFactoryPostProcessor(new MyBeanFactoryBd());
			//ac.refresh();
			//这MyBeanFactoryBd类实现beanFactoryPostProcessor接口
			for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
     
				if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
     
					BeanDefinitionRegistryPostProcessor registryProcessor =
							(BeanDefinitionRegistryPostProcessor) postProcessor;
					registryProcessor.postProcessBeanDefinitionRegistry(registry);
					registryProcessors.add(registryProcessor);
				}
				else {
     
					regularPostProcessors.add(postProcessor);
				}
			}

			//当前正在处理的BeanDefinitionRegistryPostProcessor类型的bd
			List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();

			//这里从容器里的beandeinition的名字的集合中拿出为BeanDefinitionRegistryPostProcessor的类型的名字(如果beanname存在别名,直接跳过不出理);
			//在拿的过程会进行第一次的bd的merge,意思就是假设这时候的bd中的parentName属性有值(也就是有父类)
			//假设有父类的情况:那么会先从map(这个map是存储factorybean类的beanname)如果parentname带有&这个符号,会进行截取然后从map中拿,拿不到就存进去并且返回这个值,
				然后从别名map中判断是否有别名,有的话返回别名的值,如果此时parentname
				不等于beanname,要递归再次看是否存在parentname的bd是否还有父类
				有的话继续处理,当没有父类时bd转成RootBeanDefinition,并把其存到mergeMap中,
				然后开始合并子类和父类的bd,基本是把父类存在的,把子类对应的值给父类,最后也存入mergemap中;
			//假设没有父类:就直接bd转成RootBeanDefinition,并把其存到mergeMap中,
			//所以这里会把都bd都转成RootBeanDefinition类型
			//接着会判断bd若是不抽象类,不是懒加载,等才进行然后判断是否是factorbean的子类,是的话beanname要前面要加上&这个符号,最后去判断bd是否属于
			//BeanDefinitionRegistryPostProcessor这个类型是的话就筛选出来
			//最终拿出来的name对应的bd是ConfigurationClassPostProcessor这个bd实现了工厂后置处理器的顶级和二级的接口;
			String[] postProcessorNames =
					beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
			for (String ppName : postProcessorNames) {
     
				//判断该bd是否是实现了PriorityOrdered接口
				if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
     
					//创建bean对象,然后加入集合中
					currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
					processedBeans.add(ppName);
				}
			}
			//集合排序
			sortPostProcessors(currentRegistryProcessors, beanFactory);
			//把当前的处理的configurationclassPostprocess集合加入到registryProcessors中
			registryProcessors.addAll(currentRegistryProcessors);

			//这里是重点,这里必定会先执行configurationclassPostprocessor
			//的postProcessBeanDefinitionRegistry的方法,把所有的能转换成bd对象的都转成beandefinition;
			//步骤:
			//1,扫描目前spring容器的bd类(总共6个,其中一个是开发者自己开发appconfig类)
			//2,只要appconfig类加了注解:componetsacn,componet,import,importsource,任意一个,都会把该类set一个属性如下
			//	beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_LITE);
			//上面是spring源码,就是设置了configurationClass属性为lite这个后期有用;
			//3,本例加了componetsacn注解所以后面会执行ClassPathBeanDefinitionScanner的doscan()方法把,符合要求的开发的类
			//转成beandefinition,转的步骤如下:
			//3.1,循环遍历componetsacn包文件,把文件转成spring的资源
			//3.2 通过spring的asm的框架把文件上的所有注解转成metadata资源
			//3.3 判断注解是否有includeFilters 里的注解:spring默认有component,和managebean两个
			//(这个spring自己做了扩展点可以往里加自定义的注解,然后在类上加自己的注解也可以被spring扫描到)
			//其中excludeFilters 类包含了appconfig这个类,为什么要把类剔除掉,因为该类在之前就已经转成beandefinition了
			//ClassPathScanningCandidateComponentProvider类的以下两个属性
	        //private final List includeFilters = new LinkedList<>();
	        //private final List excludeFilters = new LinkedList<>();
	        
	        //这样就把开发的类转成ScannedGenericBeanDefinition类型的bd,包含该类的所有注解metadata对象信息
	        //3.4接下来给bd进行一些属性填充如,是否是单例还是多例;是否是有懒加载,
	        //是否加了 Primary,Role,DependsOn这些注解给他填充上对应值,然后加入spring的beandefinition的map中
			invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
			
			//清空当前处理的集合
			currentRegistryProcessors.clear();

			// 这里再次去获取BeanDefinitionRegistryPostProcessor的实现类,
			//为什么要再一次拿?因为有可能我们自己写的类实现了该接口,所以也要扫描出来执行
			postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
			//这里第二次处理BeanDefinitionRegistryPostProcessor的实现类
			//且之前已经执行过得子类就不会在执行(configurationclassPostprocess),且要先执行实现orderd接口的子类
			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
			registryProcessors.addAll(currentRegistryProcessors);
			
			//第二次执行实现了orderd接口的BeanDefinitionRegistryPostProcessor的子类
			invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
			currentRegistryProcessors.clear();

			
			boolean reiterate = true;
			//这里是处理BeanDefinitionRegistryPostProcessor子类的没有实现orderd接口,那为什么要每次都去beanfactory工厂拿呢,而且还要无限循环?
			//因为有可能这个接口子类的实现方法中有可能又往beanfactory工厂设置个BeanDefinitionRegistryPostProcessor的实现类;
			//所以要这样子操作,
			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();
			}

			// 这里调用BeanFactoryPostProcessor的postProcessBeanFactory的方法
			//因为registryProcessors这个集合中都是现了这个接口
			invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
			//最后实现自定义在ac.refresh之前加入到beanfactory工厂中的BeanFactoryPostProcessor子类
			invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
		}

		else {
     
			// 这里正常是不会执行的
			invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
		}

		// 这里拿出所有的BeanFactoryPostProcessor接口的子类的名字(包含了之前实现了BeanDefinitionRegistryPostProcessor的子类)
		//后面再执行时过滤掉已经执行的bd
		String[] postProcessorNames =
				beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

		//存储优先实现了priorityOrdered接口的BeanFactoryPostProcessor的子类
		List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
		//存储实现了Ordered接口的BeanFactoryPostProcessor的子类名字
		List<String> orderedPostProcessorNames = new ArrayList<>();
		//存储上面两种以外接口的BeanFactoryPostProcessor的子类名字
		List<String> nonOrderedPostProcessorNames = new ArrayList<>();
		for (String ppName : postProcessorNames) {
     
			//过滤掉已经执行的bd
			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<>(orderedPostProcessorNames.size());
		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<>(nonOrderedPostProcessorNames.size());
		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();
	}

总结执行顺序:

1,执行BeanDefinitionRegistryPostProcessor的子类实现了PriorityOrdered接口,第一个是spring自己的configurationclassPostprocess;这个类把所有我们开发的都转成bd对象;
2,执行BeanDefinitionRegistryPostProcessor的子类的实现了ordered接口的子类;
3,执行BeanDefinitionRegistryPostProcessor的子类;
4,执行BeanDefinitionRegistryPostProcessor的子类的BeanFactoryPostProcessor的
postProcessBeanFactory方法;
5,执行在ac.refresh()之前加入了beanfactory工厂的BeanFactoryPostProcessor子类的postProcessBeanFactory方法;

6,执行BeanFactoryPostProcessor子类实现了PriorityOrdered接口的子类的postProcessBeanFactory方法;
7执行BeanFactoryPostProcessor子类实现了Ordered接口的子类的postProcessBeanFactory方法;
8执行BeanFactoryPostProcessor子类实现类的postProcessBeanFactory方法;
执行顺序从上到下,执行过就不会在执行了;

你可能感兴趣的:(spring源码)