Spring之后置处理器

361 阅读3分钟

[TOC]

Spring 7大后置处理器接口

接口名称说明接口方法调用时机
BeanPostProcessor可以自定义修改新bean实例的工厂钩子每个bean的初始化前及初始化后
具体参见方面示例,经典的使用场景如对bean进行aop
BeanFactoryPostProcessor可以自定义修改bean工厂的BeanDefinition定义spring在执行刷新上下文方法refresh()
通过后置处理器注册委托类
(PostProcessorRegistrationDelegate)回调
BeanDefinitionRegistryPostProcessor可以向bean工厂注册BeanDefinition
继承BeanFactoryPostProcessor
在所有BeanFactoryPostProcessor方法执行前执行
在同一个委托方法里被处理,执行时机参见下面详细说明
MergedBeanDefinitionPostProcessor。。。
DestructionAwareBeanPostProcessor。。。
InstantiationAwareBeanPostProcessor。。。
SmartInstantiationAwareBeanPostProcessor。。。

BeanPostProcessor

可以通过BeanPostProcessor,可以拦截容器中所有bean的创建过程,甚至修改bean实例

public interface BeanPostProcessor {
    // bean初始化方法调用前被调用
	@Nullable
	default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}
	// bean初始化方法调用后被调用
	@Nullable
	default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}
}

BeanPostProcessor示例

@Component
public class BeanPostProcessorTest implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof UserService) {
            System.out.println("4.BeanPostProcessor.前置处理postProcessBeforeInitialization");
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof UserService) {
            System.out.println("7.BeanPostProcessor.后置处理postProcessAfterInitialization");
        }
        return bean;
    }
}
@Component
public class UserService implements BeanFactoryAware, InitializingBean, DisposableBean {
    private ApplicationContext applicationContext;
    public UserService() {
        System.out.println("1.bean的实例化");
    }
    @Autowired
    public void setApplicationContext(ApplicationContext applicationContext) {
        System.out.println("2.bean的依赖注入 ApplicationContext");
        this.applicationContext = applicationContext;
    }
    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        System.out.println("3.Aware接口调用");
    }
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("6.InitializingBean.afterPropertiesSet");
    }
    @PostConstruct
    public void initMethod() {
        System.out.println("5.init-method for @PostConstruct");
    }
    @Override
    public void destroy() throws Exception {
        System.out.println("9.DisposableBean.destroy");
    }
    @PreDestroy
    public void destroyMethod() {
        System.out.println("8.destroy-method for @PreDestroy");
    }
}
@ComponentScan("com.ofwiki.postprocessor")
public class Application {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext application = new AnnotationConfigApplicationContext(Application.class);
        application.close();
    }
}

输出以下内容
1.bean的实例化
2.bean的依赖注入 ApplicationContext
3.Aware接口调用
4.BeanPostProcessor.前置处理postProcessBeforeInitialization
5.init-method for @PostConstruct
6.InitializingBean.afterPropertiesSet
7.BeanPostProcessor.后置处理postProcessAfterInitialization
8.destroy-method for @PreDestroy
9.DisposableBean.destroy

BeanFactoryPostProcessor

bean工厂的bean属性处理容器,说通俗一些就是可以管理我们的bean工厂内所有的beandefinition(未实例化)数据,可以随心所欲的修改属性。

@Component
public class BeanFactoryPostProcessorTest implements BeanFactoryPostProcessor {
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        BeanDefinition beanDefinition = beanFactory.getBeanDefinition("userService");
        System.out.println("bean class name:"+beanDefinition.getBeanClassName());
        System.out.println("当前BeanFactory中有"+beanFactory.getBeanDefinitionCount()+" 个Bean");
        System.out.println("bean names:" + Arrays.asList(beanFactory.getBeanDefinitionNames()));
    }
}

BeanFactoryPostProcessor与BeanDefinitionRegistryPostProcessor的回调时机

Spring在初始时创建bean工厂后,会调用org.springframework.context.support.AbstractApplicationContext#refresh对Spring上下文进行刷新,准备好beanFactory后,会执行invokeBeanFactoryPostProcessors(beanFactory)方法

  • invokeBeanFactoryPostProcessors(beanFactory)方法会通过委托类,调用两种后置处理器BeanFactoryPostProcessor,BeanDefinitionRegistryPostProcessor的方法
  • 会将工厂中这两种后置处理器bean和手动添加的后置处理器(this.beanFactoryPostProcessors)合并后一起调用
  • 这两个后置处理器是继承关系,会先执行所有子接口BeanDefinitionRegistryPostProcessor实例的方法,再调所有父接口BeanFactoryPostProcessor实例的方法

可以通过以下方法手动添加后置处理器

public class ApplicationTest {
    public static void main(String[] args) {
        AbstractApplicationContext context = new AnnotationConfigApplicationContext();
        context.addBeanFactoryPostProcessor(new MyBeanFactoryPostProcessor());
        context.refresh();
    }
}

详细执行顺序

  1. 执行BeanDefinitionRegistryPostProcessor的方法
    • 1.1 手动添加的BeanDefinitionRegistryPostProcessor,通过{@link AbstractApplicationContext#addBeanFactoryPostProcessor}方法添加到{@link AbstractApplicationContext#beanFactoryPostProcessors}的bean
    • 1.2 beanFactory中实现了PriorityOrdered接口的BeanDefinitionRegistryPostProcessor。如ConfigurationClassPostProcessor
    • 1.3 beanFactory中实现了Ordered接口的BeanDefinitionRegistryPostProcessor
    • 1.4 循环查找beanFactory中其它不需要排序的未执行的BeanDefinitionRegistryPostProcessor并执行,包含三种未以下三种:
      • PriorityOrdered
      • Ordered
      • 及在BeanDefinitionRegistryPostProcessor方法回调时动态注册到beanFactory的其它BeanDefinitionRegistryPostProcessor
  2. 执行BeanFactoryPostProcessor的方法
    • 2.1 执行所有BeanDefinitionRegistryPostProcessor类型的BeanFactoryPostProcessor方法
      前面的BeanDefinitionRegistryPostProcessor在执行回调前都保存在一个List<BeanFactoryPostProcessor>集合中
      循环这个集合,回调执行BeanFactoryPostProcessor的方法,所以这里BeanFactoryPostProcessor执行顺序跟前面的BeanDefinitionRegistryPostProcessor一样
    • 2.2 手动添加的BeanFactoryPostProcessor,通过{@link AbstractApplicationContext#addBeanFactoryPostProcessor}方法添加到{@link AbstractApplicationContext#beanFactoryPostProcessors}的bean
    • 2.3 beanFactory中实现了PriorityOrdered接口的BeanFactoryPostProcessor
    • 2.4 beanFactory中实现了Ordered接口的BeanFactoryPostProcessor
    • 2.5 beanFactory中其它不需要排序的BeanFactoryPostProcessor

委托类源码分析

final class PostProcessorRegistrationDelegate {
    //省略其它方法....
    
   /**
     * @param beanFactory
     * @param beanFactoryPostProcessors 手动调用AbstractApplicationContext#addBeanFactoryPostProcessor添加的后置处理器
     */
    public static void invokeBeanFactoryPostProcessors(
			ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {

		// Invoke BeanDefinitionRegistryPostProcessors first, if any.
        // 保存已经被调用过的`BeanDefinitionRegistryPostProcessor`的beanName,用于标记,避免重复调用
		Set<String> processedBeans = new HashSet<>();

		if (beanFactory instanceof BeanDefinitionRegistry) {
			BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
			// 保存手动添加的BeanFactoryPostProcessor
			List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
			// BeanDefinitionRegistryPostProcessor继承BeanFactoryPostProcessor,保存起来后续可以直接遍历集合回调BeanFactoryPostProcessor的方法
			List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();

			for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
				if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
					BeanDefinitionRegistryPostProcessor registryProcessor =
							(BeanDefinitionRegistryPostProcessor) postProcessor;
                    //1.1. 执行手动添加的`BeanDefinitionRegistryPostProcessor`
                    //     通过` AbstractApplicationContext#addBeanFactoryPostProcessor`方法添加到`AbstractApplicationContext#beanFactoryPostProcessors`的bean
					registryProcessor.postProcessBeanDefinitionRegistry(registry);
					//添加到集合中,后续回调BeanFactoryPostProcessor的方法
					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.
            // 保存指定类型的BeanDefinitionRegistryPostProcessor
			List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();

			// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
            // start --- 1.2. 回调beanFactory中实现了`PriorityOrdered`接口的`BeanDefinitionRegistryPostProcessor`
            String[] postProcessorNames =
					beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
			for (String ppName : postProcessorNames) {
			    // 从beanFactory中查找实现了PriorityOrdered接口的BeanDefinitionRegistryPostProcessor
				if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
					currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
					processedBeans.add(ppName);
				}
			}
			// 排序
			sortPostProcessors(currentRegistryProcessors, beanFactory);
			// 将实现了PriorityOrdered接口的BeanDefinitionRegistryPostProcessor合并到集合中,后续回调BeanFactoryPostProcessor的方法
			registryProcessors.addAll(currentRegistryProcessors);
            // BeanDefinitionRegistryPostProcessor方法回调
			invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
			// 清信息集合,以便后面再次使用
			currentRegistryProcessors.clear();
			//  end ---  1.2. 回调beanFactory中实现了`PriorityOrdered`接口的`BeanDefinitionRegistryPostProcessor`


			// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
            // start --- 1.3. 回调beanFactory中实现了`Ordered`接口的`BeanDefinitionRegistryPostProcessor`
			postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
			for (String ppName : postProcessorNames) {
                // 从beanFactory中查找实现了Ordered接口且未处理回调的BeanDefinitionRegistryPostProcessor
				if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
					currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
					processedBeans.add(ppName);
				}
			}
            // 排序
			sortPostProcessors(currentRegistryProcessors, beanFactory);
			// 将实现了Ordered接口的BeanDefinitionRegistryPostProcessor合并到集合中,后续回调BeanFactoryPostProcessor的方法
			registryProcessors.addAll(currentRegistryProcessors);
			// BeanDefinitionRegistryPostProcessor方法回调
			invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
            // 清信息集合,以便后面再次使用
			currentRegistryProcessors.clear();
            // end --- 1.3. 回调beanFactory中实现了`Ordered`接口的`BeanDefinitionRegistryPostProcessor`


			// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
            // start --- 1.4. 循环查找beanFactory中其它不需要排序的未执行的`BeanDefinitionRegistryPostProcessor`并执行
			boolean reiterate = true;
			while (reiterate) {
				reiterate = false;
				postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
				for (String ppName : postProcessorNames) {
				    // 查找其它未处理回调的BeanDefinitionRegistryPostProcessor
					if (!processedBeans.contains(ppName)) {
						currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
						processedBeans.add(ppName);
						// BeanDefinitionRegistryPostProcessor方法可能会beanFactory添加其它BeanDefinitionRegistryPostProcessor,因此需要再次循环
						reiterate = true;
					}
				}
				// 排序
				sortPostProcessors(currentRegistryProcessors, beanFactory);
                // 合并到集合中,后续回调BeanFactoryPostProcessor的方法
				registryProcessors.addAll(currentRegistryProcessors);
				// BeanDefinitionRegistryPostProcessor方法回调
				invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
				currentRegistryProcessors.clear();
			}
            // end --- 1.4. 循环查找beanFactory中其它不需要排序的未执行的`BeanDefinitionRegistryPostProcessor`并执行

			// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
            // 2.1 回调所有`BeanDefinitionRegistryPostProcessor`类型的`BeanFactoryPostProcessor`方法
			invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
			// 2.2 回调手动添加的`BeanFactoryPostProcessor`的方法
            // 通过AbstractApplicationContext#addBeanFactoryPostProcessor方法添加到AbstractApplicationContext#beanFactoryPostProcessors的bean
			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!
        // 获取beanFactory中所有BeanFactoryPostProcessor的beanName
		String[] postProcessorNames =
				beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

		// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
		// Ordered, and the rest.
        // 所有实现了PriorityOrdered接口BeanFactoryPostProcessor
		List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
		// 所有实现了Ordered接口BeanFactoryPostProcessor的beanName
		List<String> orderedPostProcessorNames = new ArrayList<>();
		// 其它不需要排序的BeanFactoryPostProcessor的beanName
		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.
		// 2.3 beanFactory中实现了`PriorityOrdered`接口的`BeanFactoryPostProcessor`,
        // 排序,回调
        sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
		invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

		// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
        // 2.4 beanFactory中实现了`Ordered`接口的`BeanFactoryPostProcessor`
		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.
        // 2.5 beanFactory中其它的`BeanFactoryPostProcessor`
		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();
	}
}