Spring5源码5-Bean生命周期后置处理器
主要说明三种生命周期增强器:
BeanFactoryPostProcessor:BeanFactory
后置处理器
BeanDefinitionRegistryPostProcessor:bean定义注册后置处理器
BeanFactoryPostProcessor
BeanPostProcessor:Bean后置处理器
BeanPostProcessor
MergedBeanDefinitionPostProcessor
SmartInstantiationAwareBeanPostProcessor
InstantiationAwareBeanPostProcessor
InitializingBean
DisposableBean (销毁的方案我们暂时不做说明)
1.1 什么是 BeanPostProcessor
BeanPostProcessor 是 Spring提供给我们的一个非常重要的扩展接口,并且Spring内部的很多功能也是通过 BeanPostProcessor 来完成的(目前看到最典型的就是 AnnotationAwareAspectJAutoProxyCreator 的 注入)。
1.2 BeanPostProcessor 的种类
BeanPostProcessor 在Spring 中的子类非常多(idea 显是有46个),比如
InstantiationAwareBeanPostProcessorAdapter: 在Spring 的bean加载过程中起了非常重要的作用AnnotationAwareAspectJAutoProxyCreator
: bean 创建过程中的 属性注入时起作用AspectJAwareAdvisorAutoProxyCreator
: Aspect 的 AOP 功能实现也全仰仗BeanPostProcessor 的特性。
1.3 创建时机BeanFactoryPostProcessor
:在 Spring 启动时对BeanDefinition 的创建 进行干预处理。
BeanPostProcessor
:一是Bean对应的BeanDefinition 的创建。二是Bean 实例的创建。因为在 Spring容器中,Bean的创建并非仅仅通过反射创建就结束了,在创建过程中,需要考虑到Bean针对Spring容器中的一些属性,所以BeanDefinition 中不仅仅包含了 Bean Class 文件信息,还包含了 当前Bean在Spring容器中的一些属性,比如在容器中的作用域、是否懒加载、别名等信息。当Bean 进行实例化创建时需要依赖于对应的BeanDefinition 提供对应的信息。。
而由于 BeanPostProcessor 是参与了 Bean 创建过程。所以其创建一定在普通 Bean 之前。实际上 BeanPostProcessor 的创建时在 Spring 启动时容器刷新的时候。
BeanPostProcessor 的 BeanDefinition 创建时机和普通 Bean没有区别,都是在Spring 启动时的BeanFactoryPostProcessor 中完成(确切的说是 ConfigurationClassPostProcessor 中完成)。
而BeanPostProcessor 的实例创建要优先于普通bean创建,Spring启动过程中会调用AbstractApplicationContext#registerBeanPostProcessors 方法。 在这个方法中,Spring 会从容器中获取到所有BeanPostProcessor 类型的beanName, 通过 beanFactory.getBean 方法获取到对应实例,进行排序后注册到 BeanFactory.beanPostProcessors 属性中.当容器需要执行 BeanPostProcessor 方法时可以直接从 beanPostProcessors 中获取即可。
2. 案例
分别定义几个测试类,实现bean的后置处理器:
BeanDefinitionRegistryPostProcessor:
/**
* BeanFactory的后置处理器 , PriorityOrdered, Ordered
*/
@Component
public class MyBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {
public MyBeanDefinitionRegistryPostProcessor(){
System.out.println("MyBeanDefinitionRegistryPostProcessor");
}
@Override //紧接着执行
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
System.out.println("MyBeanDefinitionRegistryPostProcessor....postProcessBeanFactory...");
}
@Override //先执行的
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
System.out.println("MyBeanDefinitionRegistryPostProcessor...postProcessBeanDefinitionRegistry...");
//增强bean定义信息的注册中心,比如自己注册组件
}
}
复制代码
BeanFactoryPostProcessor:
/**
* BeanFactory的后置处理器
*/
@Component
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
public MyBeanFactoryPostProcessor(){
System.out.println("MyBeanFactoryPostProcessor...");
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
System.out.println("BeanFactoryPostProcessor....postProcessBeanFactory==>"+beanFactory);
}
}
复制代码
BeanPostProcessor:
/**
* Bean组件的 PostProcessor;
*/
@Component
public class MyBeanPostProcessor implements BeanPostProcessor {
public MyBeanPostProcessor(){
System.out.println("MyBeanPostProcessor...");
}
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("MyBeanPostProcessor...postProcessAfterInitialization..."+bean+"==>"+beanName);
return bean;
}
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("MyBeanPostProcessor...postProcessBeforeInitialization..."+bean+"==>"+beanName);
return bean; // new Object();
}
}
复制代码
InstantiationAwareBeanPostProcessor:
@Component
public class MyInstantiationAwareBeanPostProcessor implements InstantiationAwareBeanPostProcessor {
public MyInstantiationAwareBeanPostProcessor(){
System.out.println("MyInstantiationAwareBeanPostProcessor...");
}
//初始化之前进行后置处理,Spring留给我们给这个组件创建对象的回调。
public Object postProcessBeforeInstantiation(Class> beanClass, String beanName) throws BeansException {
System.out.println("MyInstantiationAwareBeanPostProcessor...postProcessBeforeInstantiation=>"+beanClass+"--"+beanName);
//if(class.isAssFrom(Cat.class)){return new Dog()}
//如果我们自己创建了对象返回。Spring则不会帮我们创建对象,用我们自己创建的对象? 我们创建的这个对象,Spring会保存单实例?还是每次getBean都调到我们这里创建一个新的?
return null;
}
// 是否让剩下的后置处理器对bean继续进行处理
public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
//提前改变一些Spring不管的bean里面的属性
System.out.println("MyInstantiationAwareBeanPostProcessor...postProcessAfterInstantiation=>"+bean+"--"+beanName);
return true; //返回false则bean的赋值全部结束
}
//解析自定义注解进行属性值注入;pvs 封装了所有的属性信息。
public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName)
throws BeansException { //@GuiguValue();redis
System.out.println("MyInstantiationAwareBeanPostProcessor...postProcessProperties=>"+bean+"--"+beanName);
return null;
}
// public PropertyValues postProcessPropertyValues(
// PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException {
// System.out.println("MyInstantiationAwareBeanPostProcessor...postProcessProperties");
// return pvs;
// }
}
复制代码
MergedBeanDefinitionPostProcessor:
@Component
public class MyMergedBeanDefinitionPostProcessor implements MergedBeanDefinitionPostProcessor {
public MyMergedBeanDefinitionPostProcessor(){
System.out.println("MyMergedBeanDefinitionPostProcessor...");
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("MyMergedBeanDefinitionPostProcessor...postProcessBeforeInitialization...=>"+bean+"--"+beanName);
return bean; //null
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("MyMergedBeanDefinitionPostProcessor...postProcessAfterInitialization..=>"+bean+"--"+beanName);
return null;
}
@Override
public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class> beanType, String beanName) {
System.out.println("MyMergedBeanDefinitionPostProcessor...postProcessMergedBeanDefinition..=>"+beanName+"--"+beanType+"---"+beanDefinition);
}
@Override
public void resetBeanDefinition(String beanName) {
System.out.println("MyMergedBeanDefinitionPostProcessor...resetBeanDefinition.."+beanName);
}
}
复制代码
SmartInstantiationAwareBeanPostProcessor:
@Component //bean进行代理增强期间进行使用
public class MySmartInstantiationAwareBeanPostProcessor implements SmartInstantiationAwareBeanPostProcessor {
public MySmartInstantiationAwareBeanPostProcessor(){
System.out.println("MySmartInstantiationAwareBeanPostProcessor...");
}
//预测bean的类型,最后一次改变组件类型。
public Class> predictBeanType(Class> beanClass, String beanName) throws BeansException {
System.out.println("MySmartInstantiationAwareBeanPostProcessor...predictBeanType=>"+beanClass+"--"+beanName);
return null;
}
//返回我们要使用的构造器候选列表
public Constructor>[] determineCandidateConstructors(Class> beanClass, String beanName) throws BeansException {
System.out.println("MySmartInstantiationAwareBeanPostProcessor...determineCandidateConstructors=>"+beanClass+"--"+beanName);
//返回一个我们指定的构造器
return null;
}
//返回早期的bean引用,定义三级缓存中的bean信息
public Object getEarlyBeanReference(Object bean, String beanName) throws BeansException {
System.out.println("MySmartInstantiationAwareBeanPostProcessor...getEarlyBeanReference=>"+bean+"--"+beanName);
return bean; //
}
}
复制代码
InitializingBean:
@Component
public class CatInitializingBean implements InitializingBean {
public CatInitializingBean(){
System.out.println("cat被创建了...");
}
private String name;
@Value("${JAVA_HOME}") //自动赋值功能
public void setName(String name) {
System.out.println("cat....setName正在赋值调用....");
this.name = name;
}
//注解怎么定义这个是初始化方法?
public String getName() {
return name;
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("CatInitializingBean..afterPropertiesSet...");
}
@Autowired
private void init() {
System.out.println("CatInitializingBean init....");
}
}
复制代码
debug打点:在每个构造器和方法上都打上 断点,主要看看每个方法的执行时机是什么时候?
3. 源码分析
入口还是: org.springframework.context.support.AbstractApplicationContext#refresh:
// 容器刷新的十二大步骤
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// 容器启动的状态
StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");
// Prepare this context for refreshing.
// 1.准备上下文环境
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
/** 1、创建BeanFactory对象
* 2、xml解析
* 传统标签解析:bean、import等
* 自定义标签解析 如:
* 自定义标签解析流程:
* a、根据当前解析标签的头信息找到对应的namespaceUri
* b、加载spring所以jar中的spring.handlers文件。并建立映射关系
* c、根据namespaceUri从映射关系中找到对应的实现了NamespaceHandler接口的类
* d、调用类的init方法,init方法是注册了各种自定义标签的解析类
* e、根据namespaceUri找到对应的解析类,然后调用paser方法完成标签解析
* 3、把解析出来的xml标签封装成BeanDefinition对象
*/
// 2. 工厂创建:BeanFactory 第一次开始创建的时候,有xml解析逻辑
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
// 3. 预准备工厂,给容器中注册了环境信息作为单实例Bean 方便后续自动装配
// 并且放了一些后置处理器(监听、xxxAware功能)
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
// 留给子类的模板方法,允许子类继续对工厂执行一些处理
postProcessBeanFactory(beanFactory);
StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
// Invoke factory processors registered as beans in the context.
// 5. 【大核心】工厂增强:执行所有的BeanFactory 后置增强器 利用BeanFactory后置增强器对工厂进行修改或增强
// 配置类也会在这个解析
// BeanDefinitionRegistryPostProcessor BeanFactoryPostProcessor 完成对这两个接口的调用
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
// 6. 【核心】注册 所有的Bean的后置处理器
registerBeanPostProcessors(beanFactory);
beanPostProcess.end();
// Initialize message source for this context.
// 7. 初始化国际化组件
initMessageSource();
// Initialize event multicaster for this context.
// 8. 初始化事件派发 功能
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
// 9. 留给子类继续增强处理逻辑
// 这个方法着重理解模板设计模式,因为在springboot中,这个方法是用来做内嵌tomcat启动的
onRefresh();
// Check for listener beans and register them.
// 10. 注册事件监听器,从容器中获取所有的ApplicationListener
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
// 11. 【大核心】bean创建:完成BeanFactory 初始化(工厂里面所有的组件都好了)
/*
* 这个方法一定要理解要具体看
* 1、bean实例化过程
* 2、ioc
* 3、注解支持
* 4、BeanPostProcessor的执行
* 5、Aop的入口
*/
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
// 12. 发布事件
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();
contextRefresh.end();
}
}
}
复制代码
我们主要分析几个方法:
3.1 invokeBeanFactoryPostProcessors(beanFactory)BeanDefinitionRegistryPostProcessor
和 BeanFactoryPostProcessor
方法处理都是在这个步骤中。
直接看 PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors():
public static void invokeBeanFactoryPostProcessors(
ConfigurableListableBeanFactory beanFactory, List beanFactoryPostProcessors) {
// WARNING: Although it may appear that the body of this method can be easily
// refactored to avoid the use of multiple loops and multiple lists, the use
// of multiple lists and multiple passes over the names of processors is
// intentional. We must ensure that we honor the contracts for PriorityOrdered
// and Ordered processors. Specifically, we must NOT cause processors to be
// instantiated (via getBean() invocations) or registered in the ApplicationContext
// in the wrong order.
//
// Before submitting a pull request (PR) to change this method, please review the
// list of all declined PRs involving changes to PostProcessorRegistrationDelegate
// to ensure that your proposal does not result in a breaking change:
// https://github.com/spring-projects/spring-framework/issues?q=PostProcessorRegistrationDelegate+is%3Aclosed+label%3A%22status%3A+declined%22
// Invoke BeanDefinitionRegistryPostProcessors first, if any.
Set processedBeans = new HashSet<>();
// 先拿到底层默认有的BeanFactoryPostProcessor,容器会注入ConfigurationClassPostProcessor,配置类的后置处理
if (beanFactory instanceof BeanDefinitionRegistry) {
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
List regularPostProcessors = new ArrayList<>();
List registryProcessors = new ArrayList<>();
for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
BeanDefinitionRegistryPostProcessor registryProcessor =
(BeanDefinitionRegistryPostProcessor) postProcessor;
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.
List currentRegistryProcessors = new ArrayList<>();
// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
// 首先,从工厂中获取所有的BeanDefinitionRegistryPostProcessor
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
// 获取所有实现PriorityOrdered 接口的的BeanDefinitionRegistryPostProcessor
for (String ppName : postProcessorNames) {
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
// 从工厂中获取这个组件(getBean组件的创建)并放到这个集合中
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
// 利用优先级排序
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
// todo 执行这些BeanDefinitionRegistryPostProcessor
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
currentRegistryProcessors.clear();
// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
// 接下来,获取所有实现了Ordered接口的BeanDefinitionRegistryPostProcessor
for (String ppName : postProcessorNames) {
// 即使实现了Ordered 和PriorityOrdered接口,以PriorityOrdered接口为准
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, beanFactory.getApplicationStartup());
currentRegistryProcessors.clear();
// 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);
reiterate = true;
}
}
// 排序,根据类名大小写进行排序
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
// todo 执行BeanDefinitionRegistryPostProcessor.postProcessBeanDefinitionRegistry 方法
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
// 防止重复
currentRegistryProcessors.clear();
}
// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
// todo 接下来,执行BeanDefinitionRegistryPostProcessor.postProcessBeanFactory 的方法
invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
}
else {
// Invoke factory processors registered with the context instance.
invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
}
// todo 上面是执行 BeanDefinitionRegistryPostProcessor,下面是执行 BeanFactoryPostProcessor
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let the bean factory post-processors apply to them!
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
List priorityOrderedPostProcessors = new ArrayList<>();
List orderedPostProcessorNames = new ArrayList<>();
List 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.
// 首先,执行实现PriorityOrdered接口的BeanFactoryPostProcessors
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
// 接下来,执行实现Ordered接口的BeanFactoryPostProcessors
List 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.
// 最后,执行 没有实现优先级和排序 接口的BeanFactoryPostProcessors
List nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
for (String postProcessorName : nonOrderedPostProcessorNames) {
nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
// todo 执行BeanFactoryPostProcessor.postProcessBeanFactory()方法
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();
}
复制代码
获取到所有BeanDefinitionRegistryPostProcessor
并创建对象,首先,执行PriorityOrdered
接口,其次,执行Ordered
接口, 最后,执行没有实现优先级 接口,都会执行invokeBeanDefinitionRegistryPostProcessors()方法和invokeBeanFactoryPostProcessors()
方法。
3.1.1 invokeBeanDefinitionRegistryPostProcessors()
private static void invokeBeanDefinitionRegistryPostProcessors(
Collection extends BeanDefinitionRegistryPostProcessor> postProcessors, BeanDefinitionRegistry registry, ApplicationStartup applicationStartup) {
for (BeanDefinitionRegistryPostProcessor postProcessor : postProcessors) {
StartupStep postProcessBeanDefRegistry = applicationStartup.start("spring.context.beandef-registry.post-process")
.tag("postProcessor", postProcessor::toString);
// todo 核心,配置类的后置处理器在此解析配置类
postProcessor.postProcessBeanDefinitionRegistry(registry);
postProcessBeanDefRegistry.end();
}
}
复制代码
在这里会执行BeanDefinitionRegistryPostProcessor.postProcessBeanDefinitionRegistry方法。
3.1.2 invokeBeanFactoryPostProcessors()
invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
private static void invokeBeanFactoryPostProcessors(
Collection extends BeanFactoryPostProcessor> postProcessors, ConfigurableListableBeanFactory beanFactory) {
for (BeanFactoryPostProcessor postProcessor : postProcessors) {
StartupStep postProcessBeanFactory = beanFactory.getApplicationStartup().start("spring.context.bean-factory.post-process")
.tag("postProcessor", postProcessor::toString);
// todo
postProcessor.postProcessBeanFactory(beanFactory);
postProcessBeanFactory.end();
}
}
复制代码
在这里,入参都是BeanDefinitionRegistryPostProcessor 类型的,所以会执行 BeanDefinitionRegistryPostProcessor.postProcessBeanFactory方法。
3.1.3
接下来,获取到所有BeanFactoryPostProcessor
并创建对象,首先,执行PriorityOrdered
接口,其次,执行Ordered
接口, 最后,执行没有实现优先级 接口,都会执行invokeBeanFactoryPostProcessors()
方法。
本次入参是BeanFactoryPostProcessor对象,所以会执行 BeanFactoryPostProcessor.postProcessBeanFactory()方法。
3.1.4 beanFactory.getBeanNamesForType()
spring中如何根据类型获取所有的组件?
DefaultListableBeanFactory#getBeanNamesForType():
@Override
public String[] getBeanNamesForType(@Nullable Class> type, boolean includeNonSingletons, boolean allowEagerInit) {
if (!isConfigurationFrozen() || type == null || !allowEagerInit) {
// todo
return doGetBeanNamesForType(ResolvableType.forRawClass(type), includeNonSingletons, allowEagerInit);
}
...
}
复制代码
// 获取某一个组件 在容器中的名字
private String[] doGetBeanNamesForType(ResolvableType type, boolean includeNonSingletons, boolean allowEagerInit) {
List result = new ArrayList<>();
// Check all bean definitions.
// 因为Spring没有class-bean的对应信息,只能遍历所有的beanName 拿出他们所有的beanName的定义信息,再看是否指定的类型
// 只有在这里bean实例还未创建的时候,才能使用后置处理器干预 bean的类型
for (String beanName : this.beanDefinitionNames) {
// Only consider bean as eligible if the bean name is not defined as alias for some other bean.
if (!isAlias(beanName)) {
try {
RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
// Only check bean definition if it is complete.
if (!mbd.isAbstract() && (allowEagerInit ||
(mbd.hasBeanClass() || !mbd.isLazyInit() || isAllowEagerClassLoading()) &&
!requiresEagerInitForType(mbd.getFactoryBeanName()))) {
boolean isFactoryBean = isFactoryBean(beanName, mbd);
BeanDefinitionHolder dbd = mbd.getDecoratedDefinition();
boolean matchFound = false;
// containsSingleton(beanName) 是否已经创建单例对象
boolean allowFactoryBeanInit = (allowEagerInit || containsSingleton(beanName));
boolean isNonLazyDecorated = (dbd != null && !mbd.isLazyInit());
if (!isFactoryBean) {
if (includeNonSingletons || isSingleton(beanName, mbd, dbd)) {
// 是否类型匹配
matchFound = isTypeMatch(beanName, type, allowFactoryBeanInit);
}
}
else {
if (includeNonSingletons || isNonLazyDecorated ||
(allowFactoryBeanInit && isSingleton(beanName, mbd, dbd))) {
// 是否类型匹配
matchFound = isTypeMatch(beanName, type, allowFactoryBeanInit);
}
if (!matchFound) {
// In case of FactoryBean, try to match FactoryBean instance itself next.
beanName = FACTORY_BEAN_PREFIX + beanName;
if (includeNonSingletons || isSingleton(beanName, mbd, dbd)) {
matchFound = isTypeMatch(beanName, type, allowFactoryBeanInit);
}
}
}
if (matchFound) {
result.add(beanName);
}
}
}
catch (CannotLoadBeanClassException | BeanDefinitionStoreException ex) {
if (allowEagerInit) {
throw ex;
}
// Probably a placeholder: let's ignore it for type matching purposes.
LogMessage message = (ex instanceof CannotLoadBeanClassException ?
LogMessage.format("Ignoring bean class loading failure for bean '%s'", beanName) :
LogMessage.format("Ignoring unresolvable metadata in bean definition '%s'", beanName));
logger.trace(message, ex);
// Register exception, in case the bean was accidentally unresolvable.
onSuppressedException(ex);
}
catch (NoSuchBeanDefinitionException ex) {
// Bean definition got removed while we were iterating -> ignore.
}
}
}
// Check manually registered singletons too.
for (String beanName : this.manualSingletonNames) {
try {
// In case of FactoryBean, match object created by FactoryBean.
if (isFactoryBean(beanName)) {
if ((includeNonSingletons || isSingleton(beanName)) && isTypeMatch(beanName, type)) {
result.add(beanName);
// Match found for this bean: do not match FactoryBean itself anymore.
continue;
}
// In case of FactoryBean, try to match FactoryBean itself next.
beanName = FACTORY_BEAN_PREFIX + beanName;
}
// Match raw bean instance (might be raw FactoryBean).
if (isTypeMatch(beanName, type)) {
result.add(beanName);
}
}
catch (NoSuchBeanDefinitionException ex) {
// Shouldn't happen - probably a result of circular reference resolution...
logger.trace(LogMessage.format(
"Failed to check manually registered singleton with name '%s'", beanName), ex);
}
}
return StringUtils.toStringArray(result);
}
复制代码
主要步骤:
拿到所有组件的名字,beanDefinitionNames
遍历每一个组件名字
再去BeanDefinitionMap中找bean的定义信息
从定义信息中获取组件的类型
看这个类型是否匹配
3.2 registerBeanPostProcessors(beanFactory)
注册所有bean的后置处理器, PostProcessorRegistrationDelegate#registerBeanPostProcessors():
public static void registerBeanPostProcessors(
ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
// WARNING: Although it may appear that the body of this method can be easily
// refactored to avoid the use of multiple loops and multiple lists, the use
// of multiple lists and multiple passes over the names of processors is
// intentional. We must ensure that we honor the contracts for PriorityOrdered
// and Ordered processors. Specifically, we must NOT cause processors to be
// instantiated (via getBean() invocations) or registered in the ApplicationContext
// in the wrong order.
//
// Before submitting a pull request (PR) to change this method, please review the
// list of all declined PRs involving changes to PostProcessorRegistrationDelegate
// to ensure that your proposal does not result in a breaking change:
// https://github.com/spring-projects/spring-framework/issues?q=PostProcessorRegistrationDelegate+is%3Aclosed+label%3A%22status%3A+declined%22
// 获取到容器中所有的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.
int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
// Separate between BeanPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
List priorityOrderedPostProcessors = new ArrayList<>();
List internalPostProcessors = new ArrayList<>();
List orderedPostProcessorNames = new ArrayList<>();
List nonOrderedPostProcessorNames = new ArrayList<>();
for (String ppName : postProcessorNames) {
// 获取所有实现了PriorityOrdered接口
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.
// 首先,注册实现了PriorityOrdered 接口的 BeanPostProcessor
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
// Next, register the BeanPostProcessors that implement Ordered.
// 接下来,注册实现了Ordered 接口的 BeanPostProcessor
List orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
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.
// 最后,注册了普通的BeanPostProcessor
List nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
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.
// 最后,注册所有内部的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));
}
复制代码
这个步骤,将bean的后置处理器BeanPostProcessor、MergedBeanDefinitionPostProcessor、SmartInstantiationAwareBeanPostProcessor、InstantiationAwareBeanPostProcessor都注册并初始话实例。
3.3 registerListeners()
这个核心是注册监听器事件,这个我们后面再说,今天主要说明SmartInstantiationAwareBeanPostProcessor.predictBeanType()干预bean的类型。
/**
* Add beans that implement ApplicationListener as listeners.
* Doesn't affect other listeners, which can be added without being beans.
* 多播器 和监听器 是观察者模式,里面包含了所有的监听器
*/
protected void registerListeners() {
...
// 获取ApplicationListener 在ioc容器中注册的bean的名字
String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
for (String listenerBeanName : listenerBeanNames) {
// 获取所有的监听器,并保存他们的名字在
getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
}
...
}
复制代码
也会执行getBeanNamesForType()方法,前面我们简单分析过,我们直接来到:AbstractAutowireCapableBeanFactory#predictBeanType方法:
@Override
@Nullable
protected Class> predictBeanType(String beanName, RootBeanDefinition mbd, Class>... typesToMatch) {
Class> targetType = determineTargetType(beanName, mbd, typesToMatch);
// Apply SmartInstantiationAwareBeanPostProcessors to predict the
// eventual type after a before-instantiation shortcut.
if (targetType != null && !mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
boolean matchingOnlyFactoryBean = typesToMatch.length == 1 && typesToMatch[0] == FactoryBean.class;
// todo 执行SmartInstantiationAwareBeanPostProcessor.predictBeanType方法
for (SmartInstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().smartInstantiationAware) {
Class> predicted = bp.predictBeanType(targetType, beanName);
if (predicted != null &&
(!matchingOnlyFactoryBean || FactoryBean.class.isAssignableFrom(predicted))) {
return predicted;
}
}
}
return targetType;
}
复制代码
在3.1节中 执行Bean工厂的后置处理器的时候,hasInstantiationAwareBeanPostProcessors()为false,所以进入不了这个方法,原因是因为在invokeBeanFactoryPostProcessors()方法的时候,BeanPostProcessor在容器中还没有,所以不会执行。
但是,registerListeners()在registerBeanPostProcessors()方法之后,所以可以执行这个方法,也就是SmartInstantiationAwareBeanPostProcessor.predictBeanType()干预bean的组件类型。
3.4 finishBeanFactoryInitialization()
完成BeanFactory 初始化(工厂里面所有的组件都好了)。 beanFactory.preInstantiateSingletons()
-> getBean
`(beanName)->
doGetBean->
createBean`
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
...
try {
// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
// todo 提前给我们一个机会,去返回组件的代理对象
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
if (bean != null) {
return bean;
}
}
...
try {
// todo 创建对象
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (logger.isTraceEnabled()) {
logger.trace("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}
...
}
复制代码
3.4.1 resolveBeforeInstantiation(beanName, mbdToUse)
protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
Object bean = null;
if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
// Make sure bean class is actually resolved at this point.
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
Class> targetType = determineTargetType(beanName, mbd);
if (targetType != null) {
// todo InstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation()方法
bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
if (bean != null) {
bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
}
}
}
mbd.beforeInstantiationResolved = (bean != null);
}
return bean;
}
复制代码
protected Object applyBeanPostProcessorsBeforeInstantiation(Class> beanClass, String beanName) {
for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
// todo 执行
Object result = bp.postProcessBeforeInstantiation(beanClass, beanName);
if (result != null) {
return result;
}
}
return null;
}
复制代码
在这里执行 InstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation()方法。如果该方法返回true,则直接执行applyBeanPostProcessorsAfterInitialization()方法:
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
// todo 执行所有BeanPostProcessor.postProcessAfterInitialization()方法
// 所有的BeanPostProcessor类型
for (BeanPostProcessor processor : getBeanPostProcessors()) {
Object current = processor.postProcessAfterInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
复制代码
在这里执行所有BeanPostProcessor.postProcessAfterInitialization()方法。
接下来,我们看一下doCreateBean方法。
3.4.2 doCreaeBean
protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
// Instantiate the bean.
BeanWrapper instanceWrapper = null;
// 是否单例
if (mbd.isSingleton()) {
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
// todo 创建Bean实例 ,默认使用无参构造器创建的对象,组件的实例就创建了
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
Object bean = instanceWrapper.getWrappedInstance();
Class> beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
}
// Allow post-processors to modify the merged bean definition.
// MergedBeanDefinitionPostProcessor 后置处理器再来修改下BeanDefinition 信息
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
// todo 执行MergedBeanDefinitionPostProcessor.postProcessMergedBeanDefinition()方法
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Post-processing of merged bean definition failed", ex);
}
mbd.postProcessed = true;
}
}
// Eagerly cache singletons to be able to resolve circular references
// even when triggered by lifecycle interfaces like BeanFactoryAware.
// 提前暴露 单实例bean 专门来解决循坏引用的问题
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
if (logger.isTraceEnabled()) {
logger.trace("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
// 添加
// 三级缓存中Bean也会被后置处理来增强
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
// Initialize the bean instance.
Object exposedObject = bean;
try {
// todo 对象中的每个属性赋值
populateBean(beanName, mbd, instanceWrapper);
// todo 初始化Bean
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
...
return exposedObject;
}
复制代码
3.4.2.1 createBeanInstance(beanName, mbd, args)
创建bean实例,默认使用无参构造器。
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
// Make sure bean class is actually resolved at this point.
// 创建bean的类型
Class> beanClass = resolveBeanClass(mbd, beanName);
...
// Candidate constructors for autowiring?
// todo 候选的构造器 SmartInstantiationAwareBeanPostProcessor.determineCandidateConstructors()
// 后置处理器有机会在这个决定当前bean使用哪个构造器
Constructor>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
// 构造器的方式自动注入与对象创建
return autowireConstructor(beanName, mbd, ctors, args);
}
// Preferred constructors for default construction?
// 使用默认的自己设置的高优先级的构造器
ctors = mbd.getPreferredConstructors();
if (ctors != null) {
return autowireConstructor(beanName, mbd, ctors, null);
}
// No special handling: simply use no-arg constructor.
// 默认使用无参构造器为当前组件创建对象
return instantiateBean(beanName, mbd);
}
复制代码
在determineConstructorsFromBeanPostProcessors方法中可以决定使用构造器。
protected Constructor>[] determineConstructorsFromBeanPostProcessors(@Nullable Class> beanClass, String beanName)
throws BeansException {
if (beanClass != null && hasInstantiationAwareBeanPostProcessors()) {
for (SmartInstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().smartInstantiationAware) {
// todo 执行SmartInstantiationAwareBeanPostProcessor.determineCandidateConstructors()方法
Constructor>[] ctors = bp.determineCandidateConstructors(beanClass, beanName);
if (ctors != null) {
return ctors;
}
}
}
return null;
}
复制代码
在这里执行SmartInstantiationAwareBeanPostProcessor.determineCandidateConstructors()方法。
3.4.2.2 applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName)
protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class> beanType, String beanName) {
// todo 执行MergedBeanDefinitionPostProcessor.postProcessMergedBeanDefinition()方法
for (MergedBeanDefinitionPostProcessor processor : getBeanPostProcessorCache().mergedDefinition) {
processor.postProcessMergedBeanDefinition(mbd, beanType, beanName);
}
}
复制代码
在这里执行MergedBeanDefinitionPostProcessor.postProcessMergedBeanDefinition()方法。
3.4.2.3 populateBean(beanName, mbd, instanceWrapper)
对每个属性进行赋值操作。
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
...
// 属性赋值之前,后置处理器可以提前准备些东西
// @AutoWired 赋值也在这里 AutowiredAnnotationBeanPostProcessor(直接返回true 没有其他的处理),可以中断初始化行为
//
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
// todo 执行InstantiationAwareBeanPostProcessor.postProcessAfterInstantiation() 方法
if (!bp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
return;
}
}
} // 以上的后置处理器可以中断下面的初始化行为
...
boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);
PropertyDescriptor[] filteredPds = null;
if (hasInstAwareBpps) {
if (pvs == null) {
// xml中property标签指定的
pvs = mbd.getPropertyValues();
}
// 注解版的属性赋值 后置处理器处理属性(真正的自动装配)
for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
// todo 执行InstantiationAwareBeanPostProcessor.postProcessProperties() 方法
PropertyValues pvsToUse = bp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
pvsToUse = bp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
return;
}
}
pvs = pvsToUse; // 封装了当前bean的所有属性名和值,可以由后置处理器处理得到
}
}
...
if (pvs != null) { // 把以前处理好的PropertyValues 给bean里面设置一下,主要是上面步骤没有给bean里面设置的属性
// xml版 的所有配置会来到这里 给属性赋值
applyPropertyValues(beanName, mbd, bw, pvs);
}
}
复制代码
这里,会执行2个后置处理器的方法:
执行InstantiationAwareBeanPostProcessor.postProcessAfterInstantiation() 方法
执行InstantiationAwareBeanPostProcessor.postProcessProperties() 方法
3.4.2.4 initializeBean(beanName, exposedObject, mbd)
对bean进行初始化操作。
protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction
复制代码
在这里,执行三个后置处理器的方法:
执行所有BeanPostProcessor.postProcessBeforeInitialization()方法
实现InitializingBean 的接口,执行初始化方法实现InitializingBean.afterPropertiesSet() 方法
执行所有BeanPostProcessor.postProcessAfterInitialization()方法
到此,bean生命周期的所有后置处理器方法的执行时机已经全部展示出来