【死磕源码系列】BeanDefinitionRegistryPostProcessor作用及源码分析

浅浅的花香味﹌ 2022-12-07 15:26 295阅读 0赞

BeanDefinitionRegistryPostProcessor接口实现了BeanFactoryPostProcessor接口,BeanFactoryPostProcessor接口的作用是在bean已经注册完成为BeanDefinition,但是还未实例化之前修改BeanDefinition属性;BeanDefinitionRegistryPostProcessor接口提供了一个通过代码形式来注册bean到IOC容器的钩子方法;

1.先看下源码
  1. /** * Extension to the standard {@link BeanFactoryPostProcessor} SPI, allowing for * the registration of further bean definitions <i>before</i> regular * BeanFactoryPostProcessor detection kicks in. In particular, * BeanDefinitionRegistryPostProcessor may register further bean definitions * which in turn define BeanFactoryPostProcessor instances. * * @author Juergen Hoeller * @since 3.0.1 * @see org.springframework.context.annotation.ConfigurationClassPostProcessor */
  2. public interface BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessor {
  3. /** * Modify the application context's internal bean definition registry after its * standard initialization. All regular bean definitions will have been loaded, * but no beans will have been instantiated yet. This allows for adding further * bean definitions before the next post-processing phase kicks in. * @param registry the bean definition registry used by the application context * @throws org.springframework.beans.BeansException in case of errors */
  4. void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException;
  5. }

BeanDefinitionRegistryPostProcessor接口会在bean实例化之前调用postProcessBeanDefinitionRegistry、postProcessBeanFactory方法对指定的bean进行实例化及修改BeanDefinition;

2.org.springframework.context.support.PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors方法是调用处理器方法的入口

首先看下refresh方法:

  1. @Override
  2. public void refresh() throws BeansException, IllegalStateException {
  3. synchronized (this.startupShutdownMonitor) {
  4. // Prepare this context for refreshing.
  5. prepareRefresh();
  6. // Tell the subclass to refresh the internal bean factory.
  7. ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
  8. // Prepare the bean factory for use in this context.
  9. prepareBeanFactory(beanFactory);
  10. try {
  11. // Allows post-processing of the bean factory in context subclasses.
  12. postProcessBeanFactory(beanFactory);
  13. // 调用BeanFactoryPostProcessor接口实现类及BeanDefinitionRegistryPostProcessor实现类的入口方法
  14. invokeBeanFactoryPostProcessors(beanFactory);
  15. // Register bean processors that intercept bean creation.
  16. registerBeanPostProcessors(beanFactory);
  17. // Initialize message source for this context.
  18. initMessageSource();
  19. // Initialize event multicaster for this context.
  20. initApplicationEventMulticaster();
  21. // Initialize other special beans in specific context subclasses.
  22. onRefresh();
  23. // Check for listener beans and register them.
  24. registerListeners();
  25. // Instantiate all remaining (non-lazy-init) singletons.
  26. finishBeanFactoryInitialization(beanFactory);
  27. // Last step: publish corresponding event.
  28. finishRefresh();
  29. }
  30. catch (BeansException ex) {
  31. if (logger.isWarnEnabled()) {
  32. logger.warn("Exception encountered during context initialization - " +
  33. "cancelling refresh attempt: " + ex);
  34. }
  35. // Destroy already created singletons to avoid dangling resources.
  36. destroyBeans();
  37. // Reset 'active' flag.
  38. cancelRefresh(ex);
  39. // Propagate exception to caller.
  40. throw ex;
  41. }
  42. finally {
  43. // Reset common introspection caches in Spring's core, since we
  44. // might not ever need metadata for singleton beans anymore...
  45. resetCommonCaches();
  46. }
  47. }
  48. }

上述源码中invokeBeanFactoryPostProcessors是调用BeanDefinitionRegistryPostProcessor的入口,接下来看下具体的方法调用PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors:

  1. public static void invokeBeanFactoryPostProcessors(
  2. ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
  3. // Invoke BeanDefinitionRegistryPostProcessors first, if any.
  4. Set<String> processedBeans = new HashSet<>();
  5. if (beanFactory instanceof BeanDefinitionRegistry) {
  6. BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
  7. List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
  8. List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
  9. for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
  10. if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
  11. BeanDefinitionRegistryPostProcessor registryProcessor =
  12. (BeanDefinitionRegistryPostProcessor) postProcessor;
  13. registryProcessor.postProcessBeanDefinitionRegistry(registry);
  14. registryProcessors.add(registryProcessor);
  15. }
  16. else {
  17. regularPostProcessors.add(postProcessor);
  18. }
  19. }
  20. // Do not initialize FactoryBeans here: We need to leave all regular beans
  21. // uninitialized to let the bean factory post-processors apply to them!
  22. // Separate between BeanDefinitionRegistryPostProcessors that implement
  23. // PriorityOrdered, Ordered, and the rest.
  24. List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
  25. //首先,所有实现了PriorityOrdered接口BeanDefinitionRegistryPostProcessors实现类实例化并调用后置处理方法
  26. // First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
  27. String[] postProcessorNames =
  28. beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
  29. for (String ppName : postProcessorNames) {
  30. if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
  31. currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
  32. processedBeans.add(ppName);
  33. }
  34. }
  35. sortPostProcessors(currentRegistryProcessors, beanFactory);
  36. registryProcessors.addAll(currentRegistryProcessors);
  37. invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
  38. currentRegistryProcessors.clear();
  39. //接着,对所有实现了Ordered接口的BeanDefinitionRegistryPostProcessors实现类进行实例化并调用后置处理方法
  40. // Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
  41. postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
  42. for (String ppName : postProcessorNames) {
  43. if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
  44. currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
  45. processedBeans.add(ppName);
  46. }
  47. }
  48. sortPostProcessors(currentRegistryProcessors, beanFactory);
  49. registryProcessors.addAll(currentRegistryProcessors);
  50. invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
  51. currentRegistryProcessors.clear();
  52. //最后,调用所有其它的BeanDefinitionRegistryPostProcessors实现类,自定义的BeanDefinitionRegistryPostProcessors实现类就是在这里被实例化并调用后置处理器方法的
  53. // Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
  54. boolean reiterate = true;
  55. while (reiterate) {
  56. reiterate = false;
  57. postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
  58. for (String ppName : postProcessorNames) {
  59. if (!processedBeans.contains(ppName)) {
  60. currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
  61. processedBeans.add(ppName);
  62. reiterate = true;
  63. }
  64. }
  65. sortPostProcessors(currentRegistryProcessors, beanFactory);
  66. registryProcessors.addAll(currentRegistryProcessors);
  67. //调用处理方法,注册相关bean到IOC容器之中
  68. invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
  69. currentRegistryProcessors.clear();
  70. }
  71. //现在,调用所有的postProcessBeanFactory方法对BeanDefinition进行修改
  72. // Now, invoke the postProcessBeanFactory callback of all processors handled so far.
  73. invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
  74. invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
  75. }
  76. else {
  77. //调用BeanFactoryPostProcessor的后置处理方法
  78. // Invoke factory processors registered with the context instance.
  79. invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
  80. }
  81. // Do not initialize FactoryBeans here: We need to leave all regular beans
  82. // uninitialized to let the bean factory post-processors apply to them!
  83. String[] postProcessorNames =
  84. beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
  85. // Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
  86. // Ordered, and the rest.
  87. List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
  88. List<String> orderedPostProcessorNames = new ArrayList<>();
  89. List<String> nonOrderedPostProcessorNames = new ArrayList<>();
  90. for (String ppName : postProcessorNames) {
  91. if (processedBeans.contains(ppName)) {
  92. // skip - already processed in first phase above
  93. }
  94. else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
  95. priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
  96. }
  97. else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
  98. orderedPostProcessorNames.add(ppName);
  99. }
  100. else {
  101. nonOrderedPostProcessorNames.add(ppName);
  102. }
  103. }
  104. // First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
  105. sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
  106. invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
  107. // Next, invoke the BeanFactoryPostProcessors that implement Ordered.
  108. List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
  109. for (String postProcessorName : orderedPostProcessorNames) {
  110. orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
  111. }
  112. sortPostProcessors(orderedPostProcessors, beanFactory);
  113. invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
  114. // Finally, invoke all other BeanFactoryPostProcessors.
  115. List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
  116. for (String postProcessorName : nonOrderedPostProcessorNames) {
  117. nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
  118. }
  119. invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
  120. // Clear cached merged bean definitions since the post-processors might have
  121. // modified the original metadata, e.g. replacing placeholders in values...
  122. beanFactory.clearMetadataCache();
  123. }

上述源码中文注解部分是BeanDefinitionRegistryPostProcessor实现类的实例化及方法调用的入口,会在BeanFactoryPostProcessors实现类方法实例化及方法调用之前执行;

3.示例代码
  1. public class TestBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {
  2. @Override
  3. public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
  4. RootBeanDefinition beanDefinition = new RootBeanDefinition(AsyncLogHttpClientServiceImpl.class);
  5. //将指定的bean注册到IOC容器之中
  6. registry.registerBeanDefinition(AsyncLogHttpClientServiceImpl.class.getName(), beanDefinition);
  7. }
  8. @Override
  9. public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
  10. //在这里可以对已经注册到容器之中的BeanDefinition的属性进行修改
  11. }
  12. }

GitHub地址:https://github.com/mingyang66/spring-parent/tree/master/doc/base

发表评论

表情:
评论列表 (有 0 条评论,295人围观)

还没有评论,来说两句吧...

相关阅读