Spring 生命周期之 invokeBeanFactoryPostProcessors(三)

606 阅读1分钟

1、源码解析

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


		Set<String> processedBeans = new HashSet<>();

		if (beanFactory instanceof BeanDefinitionRegistry) {
			BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
			List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
			List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();

// 这里是拿到前面添加的 BeanFactoryPostProcessor
			for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
//			如果 BeanFactoryPostProcessor 是 BeanDefinitionRegistryPostProcessor 的话就调用它的 postProcessBeanDefinitionRegistry 方法。
				if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
					BeanDefinitionRegistryPostProcessor registryProcessor =
							(BeanDefinitionRegistryPostProcessor) postProcessor;
					registryProcessor.postProcessBeanDefinitionRegistry(registry);
//					这里添加到 registryProcessors 中
					registryProcessors.add(registryProcessor);
				}
				else {
//				这里添加到常规的 PostProcessors 中,BeanFactoryPostProcessor做了区分
					regularPostProcessors.add(postProcessor);
				}
			}

//			下面就开始对 BeanDefinitionRegistryPostProcessor 开始按顺序执行了
			List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();

// 这里拿到所有的 BeanDefinitionRegistryPostProcessor 类型的 Bean 名称,@Component这些注解还没有被扫描进 IOC 中
			String[] postProcessorNames =
					beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
			for (String ppName : postProcessorNames) {
//			这里判断 ppName 是否是 PriorityOrdered  或者是 PriorityOrdered 的子类
				if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
					currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
//					标记当前 Bean 已被处理
					processedBeans.add(ppName);
				}
			}
//			这里对 BeanDefinitionRegistryPostProcessor 再排序,默认规则是根据 order
			sortPostProcessors(currentRegistryProcessors, beanFactory);
			registryProcessors.addAll(currentRegistryProcessors);
//			这里调用 BeanDefinitionRegistryPostProcessor 的 postProcessBeanDefinitionRegistry 方法。
			invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
			currentRegistryProcessors.clear();

			// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
//			这边再获取 BeanDefinitionRegistryPostProcessor 类型的 Bean 名称,为什么这里还是要再获取而不用上面的呢,
//          考虑到上面调用的 postProcessBeanDefinitionRegistry 方法会注册进新的 BeanDefinitionRegistryPostProcessor
			postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
			for (String ppName : postProcessorNames) {
//			这里排除已被处理的 Bean 并且拿到实现了 Ordered 或者是子类的 BeanDefinitionRegistryPostProcessor
				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);
//			调用 BeanDefinitionRegistryPostProcessor 的 postProcessBeanDefinitionRegistry 方法
			invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
			currentRegistryProcessors.clear();

//			接下来就是处理上面新注册的 BeanDefinitionRegistryPostProcessor 了
			// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
			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);
//						这里做这个标识是防止在 postProcessBeanDefinitionRegistry 中新注册了 BeanDefinitionRegistryPostProcessor 进来而没有被执行到。
//                      所以说要循环处理
						reiterate = true;
					}
				}
//				排序
				sortPostProcessors(currentRegistryProcessors, beanFactory);
				registryProcessors.addAll(currentRegistryProcessors);
//              调用 BeanDefinitionRegistryPostProcessor 的 postProcessBeanDefinitionRegistry 方法。
				invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
				currentRegistryProcessors.clear();
			}

			// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
//			这里的话就调用 registryProcessors 的 postProcessBeanFactory 方法
			invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
//			这里调用的是不是 BeanDefinitionRegistryPostProcessor 类型的 BeanFactoryPostProcessor 的 postProcessBeanFactory 方法。
			invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
		}

		else {
			// Invoke factory processors registered with the context instance.
			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 类型 ,BeanDefinitionRegistryPostProcessor 的父类
		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) {
//		跳过已被处理的.因为在后面也执行了 postProcessBeanFactory 可能会注册进 BeanFactoryPostProcessor,所以这里还有处理逻辑
//以下是排序操作
			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);
			}
		}

//以下是按顺序执行 BeanFactoryPostProcessor 的 postProcessBeanFactory 方法.
		// 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.1、规则总结

以上总结来说就是:

会依次执行 BeanFactoryPostProcessor 与 BeanDefinitionRegistryPostProcessor 接口的相关方法。

如果是常规方法注册的,比如 @Component 注解注册那么会按照以下的顺序执行:

实现 PriorityOrdered 的 BeanDefinitionRegistryPostProcessor postProcessBeanDefinitionRegistry 方法先执行,order 越小越先执行;

实现 Ordered 的 BeanDefinitionRegistryPostProcessor postProcessBeanDefinitionRegistry 方法执行,order 越小越先执行;

未实现 PriorityOrdered 或者 Ordered 的 BeanDefinitionRegistryPostProcessor postProcessBeanDefinitionRegistry 方法执行,order 越小越先执行;

【1】

以上顺序的 postProcessBeanFactory 方法执行。

最后就是 BeanFactoryPostProcessor 的 postProcessBeanFactory 方法执行。

如果是使用 BeanDefinitionRegistryPostProcessor postProcessBeanDefinitionRegistry 方法注册的 BeanDefinitionRegistryPostProcessor 则遵循谁先注册谁先执行,执行顺序会插入到标记【1】的位置。

如果是使用 BeanDefinitionRegistryPostProcessor postProcessBeanFactory 注册的 BeanDefinitionRegistryPostProcessor,那么就有点特殊了,它的 postProcessBeanDefinitionRegistry 不会被执行,不知道是不

是一个 Spring 的一个 bug,看源码是因为通过未实现排序接口的 BeanDefinitionRegistryPostProcessor 的postProcessBeanFactory 方法注册的 BeanDefinitionRegistryPostProcessor 实现类,后面是没有执行 postProcessBeanDefinitionRegistry 方法的机会的。

如果以上看不明白,那么可以自己复制以下代码尝试一下:

@Component
public class Test1BeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor, PriorityOrdered {

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        System.out.println("我是Test1的postProcessBeanDefinitionRegistry");
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        System.out.println("我是Test1的postProcessBeanFactory");
    }

    @Override
    public int getOrder() {
        return 100;
    }
}


@Component
public class Test1BeanFactoryPostProcessor implements BeanFactoryPostProcessor, PriorityOrdered {

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        System.out.println("我是Test1BeanFactoryPostProcessor的postProcessBeanFactory");
    }

    @Override
    public int getOrder() {
        return 56;
    }
}


@Component
public class Test2BeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor, PriorityOrdered {

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        System.out.println("我是Test2的postProcessBeanDefinitionRegistry");
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        System.out.println("我是Test2的postProcessBeanFactory");
    }

    @Override
    public int getOrder() {
        return 99;
    }
}


@Component
public class Test3BeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor, PriorityOrdered {

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        registry.registerBeanDefinition("test9BeanDefinitionRegistryPostProcessor",new RootBeanDefinition(Test9BeanDefinitionRegistryPostProcessor.class));
        System.out.println("我是Test3的postProcessBeanDefinitionRegistry");
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        System.out.println("我是Test3的postProcessBeanFactory");
        beanFactory.registerSingleton("test6BeanDefinitionRegistryPostProcessor",new Test6BeanDefinitionRegistryPostProcessor());
    }

    @Override
    public int getOrder() {
        return 99;
    }
}


@Component
public class Test4BeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor{

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        registry.registerBeanDefinition("test5BeanDefinitionRegistryPostProcessor",new RootBeanDefinition(Test5BeanDefinitionRegistryPostProcessor.class));
        System.out.println("我是Test4的postProcessBeanDefinitionRegistry");
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        System.out.println("我是Test4的postProcessBeanFactory");
        beanFactory.registerSingleton("test7BeanDefinitionRegistryPostProcessor",new Test7BeanDefinitionRegistryPostProcessor());
    }

}


public class Test5BeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor , PriorityOrdered {

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        System.out.println("我是Test5的postProcessBeanDefinitionRegistry");
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        System.out.println("我是Test5的postProcessBeanFactory");
    }

    @Override
    public int getOrder() {
        return 1;
    }
}


public class Test6BeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor{

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        System.out.println("我是Test6的postProcessBeanDefinitionRegistry");
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        System.out.println("我是Test6的postProcessBeanFactory");
    }

}


public class Test7BeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor{

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        System.out.println("我是Test7的postProcessBeanDefinitionRegistry");
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        System.out.println("我是Test7的postProcessBeanFactory");
    }

}

@Component
public class Test8BeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor, Ordered {

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        System.out.println("我是Test8的postProcessBeanDefinitionRegistry");
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        System.out.println("我是Test8的postProcessBeanFactory");
    }

    @Override
    public int getOrder() {
        return 44;
    }
}

public class Test9BeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        System.out.println("我是Test9的postProcessBeanDefinitionRegistry");
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        System.out.println("我是Test9的postProcessBeanFactory");
    }
}

最后再提一下一个特殊的 BeanDefinitionRegistryPostProcessor -> ConfigurationClassPostProcessor,它会处理项目中的 @Component@Import 等这些注解然后将 BeanDefinition 加载到 IOC 当中的,当然了,后续再讲。