BeanPostProcessor
首先咱們應當瞭解到在spring體系中BeanPostProcessor
是什麼、加載流程java
BeanPostProcessor
也也稱爲後置處理器。在spring容加載流程。spring
// Prepare this context for refreshing. prepareRefresh(); // 獲取beanFactory並加載容器中定義的bean信息 ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); // Prepare the bean factory for use in this context. prepareBeanFactory(beanFactory); try { // 歸類bean工廠的後置處理器 postProcessBeanFactory(beanFactory); // 處理這些bean工廠的後置處理器 invokeBeanFactoryPostProcessors(beanFactory); // 調用全部實現了beanpostprocessor接口的類。(先加載實現了priority接口的,而後加載order的,最後加載剩餘的) 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(); }
因此由上能夠看出,在registerBeanPostProcessors
這一步的時候會劃分容器中各類後置處理器,首先歸類有@Priority
註解,其次歸類有@Order
註解。最後劃分其它的。ide
// 1 sortPostProcessors(priorityOrderedPostProcessors, beanFactory); registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors); // 2 sortPostProcessors(orderedPostProcessors, beanFactory); registerBeanPostProcessors(beanFactory, orderedPostProcessors); // 3 registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors); // Finally, re-register all internal BeanPostProcessors. sortPostProcessors(internalPostProcessors, beanFactory); registerBeanPostProcessors(beanFactory, internalPostProcessors);
這樣,就將全部的後置處理器註冊到容器中。後續在容器啓動的過程當中,會經過反射的方式調用各個實現了BeanPostProcessor
的實現類的beforexxxx
和afterxxx
的方法來作進一步的處理。post
有了以上基礎,就能夠去dubbo包中找到各自的
xxxBeanPostProcessor
了。
this
ServiceAnnotationBeanPostProcessor
BeanDefinitionRegistryPostProcessor繼承自BeanFactoryPostProcessor,是一種比較特殊的BeanFactoryPostProcessor。BeanDefinitionRegistryPostProcessor中定義的postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry)方法 能夠讓咱們實現自定義的註冊bean定義的邏輯。
code
從以上論述能夠看出實現BeanDefinitionRegistryPostProcessor
的做用就是向spring容器中註冊響應的bean實例。blog
@Override public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { // 讀取配置中聲明的dubbo掃描類 Set<String> resolvedPackagesToScan = resolvePackagesToScan(packagesToScan); if (!CollectionUtils.isEmpty(resolvedPackagesToScan)) { // 將加有@Service註解的類註冊到spring容器中 registerServiceBeans(resolvedPackagesToScan, registry); } else { if (logger.isWarnEnabled()) { logger.warn("packagesToScan is empty , ServiceBean registry will be ignored!"); } } }
下面就分析registerServiceBeans
的處理過程。繼承
basePackages
,將@Service
註解的類放到一個set集合中。@Service
的類是否被掃面到。registerServiceBean
循環遍歷這個集合,並將它們注入到spring容器中。