- Author: HuiFer
- 源码阅读仓库: SourceHot-Spring
- 作用: 定制或修改
BeanDefinition
的属性
publicclassChangeAttrBeanPostProcessorimplementsBeanFactoryPostProcessor { privateSet<String> attr; publicChangeAttrBeanPostProcessor() { attr = newHashSet<>(); } publicSet<String> getAttr() { returnattr; } publicvoidsetAttr(Set<String> attr) { this.attr = attr; } @OverridepublicvoidpostProcessBeanFactory(ConfigurableListableBeanFactorybeanFactory) throwsBeansException { String[] beanDefinitionNames = beanFactory.getBeanDefinitionNames(); for (StringbeanName : beanDefinitionNames) { BeanDefinitionbeanDefinition = beanFactory.getBeanDefinition(beanName); StringValueResolverstringValueResolver = newStringValueResolver() { @OverridepublicStringresolveStringValue(StringstrVal) { if (attr.contains(strVal)) { return"隐藏属性"; } else { returnstrVal; } } }; BeanDefinitionVisitorvisitor = newBeanDefinitionVisitor(stringValueResolver); visitor.visitBeanDefinition(beanDefinition); } } }
publicclassBeanFactoryPostProcessorSourceCode { publicstaticvoidmain(String[] args) { ApplicationContextcontext = newClassPathXmlApplicationContext("BeanFactoryPostProcessor-demo.xml"); Appleapple = context.getBean("apple", Apple.class); System.out.println(apple); } }
<?xml version="1.0" encoding="UTF-8"?> <beansxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://www.springframework.org/schema/beans"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <beanid="removeAttrBeanPostProcessor"class="com.huifer.source.spring.beanPostProcessor.ChangeAttrBeanPostProcessor"> <propertyname="attr"> <set> <value>hc</value> </set> </property> </bean> <beanid="apple"class="com.huifer.source.spring.bean.Apple"> <propertyname="name"value="hc"/> </bean> </beans>
org.springframework.context.support.AbstractApplicationContext#refresh
invokeBeanFactoryPostProcessors(beanFactory);
protectedvoidinvokeBeanFactoryPostProcessors(ConfigurableListableBeanFactorybeanFactory) { PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors()); // Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime// (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) { beanFactory.addBeanPostProcessor(newLoadTimeWeaverAwareProcessor(beanFactory)); beanFactory.setTempClassLoader(newContextTypeMatchClassLoader(beanFactory.getBeanClassLoader())); } }
org.springframework.context.support.PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors(org.springframework.beans.factory.config.ConfigurableListableBeanFactory, java.util.List<org.springframework.beans.factory.config.BeanFactoryPostProcessor>)
publicstaticvoidinvokeBeanFactoryPostProcessors( ConfigurableListableBeanFactorybeanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) { // Invoke BeanDefinitionRegistryPostProcessors first, if any.Set<String> processedBeans = newHashSet<>(); // 判断是否为BeanDefinitionRegistry类if (beanFactoryinstanceofBeanDefinitionRegistry) { BeanDefinitionRegistryregistry = (BeanDefinitionRegistry) beanFactory; // 存放 BeanFactoryPostProcessorList<BeanFactoryPostProcessor> regularPostProcessors = newArrayList<>(); // 存放 BeanDefinitionRegistryPostProcessorList<BeanDefinitionRegistryPostProcessor> registryProcessors = newArrayList<>(); // 2.首先处理入参中的beanFactoryPostProcessorsfor (BeanFactoryPostProcessorpostProcessor : beanFactoryPostProcessors) { // 判断是否是BeanDefinitionRegistryPostProcessorif (postProcessorinstanceofBeanDefinitionRegistryPostProcessor) { BeanDefinitionRegistryPostProcessorregistryProcessor = (BeanDefinitionRegistryPostProcessor) postProcessor; //registryProcessor.postProcessBeanDefinitionRegistry(registry); // BeanDefinitionRegistryPostProcessor 添加// 执行 postProcessBeanFactoryregistryProcessors.add(registryProcessor); } // 这部分else 内容就是 BeanFactoryPostProcessorelse { // BeanFactoryPostProcessor 添加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<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = newArrayList<>(); // First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered./** * 调用实现{@link PriorityOrdered}\{@link BeanDefinitionRegistryPostProcessor} * todo: 2020年1月16日 解析方法 * {@link DefaultListableBeanFactory#getBeanNamesForType(java.lang.Class, boolean, boolean)} */String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false); for (StringppName : postProcessorNames) { if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) { currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class)); processedBeans.add(ppName); } } // 排序OrdersortPostProcessors(currentRegistryProcessors, beanFactory); registryProcessors.addAll(currentRegistryProcessors); invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry); currentRegistryProcessors.clear(); // Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false); for (StringppName : postProcessorNames) { 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); currentRegistryProcessors.clear(); // Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.booleanreiterate = true; while (reiterate) { reiterate = false; postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false); for (StringppName : postProcessorNames) { if (!processedBeans.contains(ppName)) { currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class)); processedBeans.add(ppName); reiterate = true; } } sortPostProcessors(currentRegistryProcessors, beanFactory); registryProcessors.addAll(currentRegistryProcessors); invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry); currentRegistryProcessors.clear(); } // Now, invoke the postProcessBeanFactory callback of all processors handled so far.invokeBeanFactoryPostProcessors(registryProcessors, beanFactory); 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 处理String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false); // Separate between BeanFactoryPostProcessors that implement PriorityOrdered,// Ordered, and the rest.List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = newArrayList<>(); List<String> orderedPostProcessorNames = newArrayList<>(); List<String> nonOrderedPostProcessorNames = newArrayList<>(); for (StringppName : postProcessorNames) { if (processedBeans.contains(ppName)) { // skip - already processed in first phase above// 处理过的跳过 } elseif (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) { priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class)); } elseif (beanFactory.isTypeMatch(ppName, Ordered.class)) { orderedPostProcessorNames.add(ppName); } else { nonOrderedPostProcessorNames.add(ppName); } } // First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.sortPostProcessors(priorityOrderedPostProcessors, beanFactory); invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory); // Next, invoke the BeanFactoryPostProcessors that implement Ordered.List<BeanFactoryPostProcessor> orderedPostProcessors = newArrayList<>(); for (StringpostProcessorName : orderedPostProcessorNames) { orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class)); } sortPostProcessors(orderedPostProcessors, beanFactory); invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory); // Finally, invoke all other BeanFactoryPostProcessors.// 配置文件中自定义的 BeanFactoryPostProcessor 注册List<BeanFactoryPostProcessor> nonOrderedPostProcessors = newArrayList<>(); for (StringpostProcessorName : 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(); }
protectedvoidregisterBeanPostProcessors(ConfigurableListableBeanFactorybeanFactory) { PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this); }
publicstaticvoidregisterBeanPostProcessors( ConfigurableListableBeanFactorybeanFactory, AbstractApplicationContextapplicationContext) { // 获取 BeanPostProcessorString[] 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.// 获取数量intbeanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length; beanFactory.addBeanPostProcessor(newBeanPostProcessorChecker(beanFactory, beanProcessorTargetCount)); // Separate between BeanPostProcessors that implement PriorityOrdered,// Ordered, and the rest.// BeanPostProcessor 通过PriorityOrdered保证顺序List<BeanPostProcessor> priorityOrderedPostProcessors = newArrayList<>(); // MergedBeanDefinitionPostProcessorList<BeanPostProcessor> internalPostProcessors = newArrayList<>(); // 有序的 BeanPostProcessorList<String> orderedPostProcessorNames = newArrayList<>(); // 无序的 BeanPostProcessorList<String> nonOrderedPostProcessorNames = newArrayList<>(); for (StringppName : postProcessorNames) { if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) { BeanPostProcessorpp = beanFactory.getBean(ppName, BeanPostProcessor.class); priorityOrderedPostProcessors.add(pp); // 类型判断放入相应的listif (ppinstanceofMergedBeanDefinitionPostProcessor) { internalPostProcessors.add(pp); } } elseif (beanFactory.isTypeMatch(ppName, Ordered.class)) { orderedPostProcessorNames.add(ppName); } else { nonOrderedPostProcessorNames.add(ppName); } } // First, register the BeanPostProcessors that implement PriorityOrdered./** * 有{@link org.springframework.core.annotation.Order} 相关操作 */sortPostProcessors(priorityOrderedPostProcessors, beanFactory); // 注册 BeanPostProcessor 和 PriorityOrdered 实现registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors); // Next, register the BeanPostProcessors that implement Ordered.List<BeanPostProcessor> orderedPostProcessors = newArrayList<>(); for (StringppName : orderedPostProcessorNames) { BeanPostProcessorpp = beanFactory.getBean(ppName, BeanPostProcessor.class); orderedPostProcessors.add(pp); if (ppinstanceofMergedBeanDefinitionPostProcessor) { internalPostProcessors.add(pp); } } sortPostProcessors(orderedPostProcessors, beanFactory); // 注册 实现Order 和 BeanPostProcessorregisterBeanPostProcessors(beanFactory, orderedPostProcessors); // Now, register all regular BeanPostProcessors.List<BeanPostProcessor> nonOrderedPostProcessors = newArrayList<>(); for (StringppName : nonOrderedPostProcessorNames) { BeanPostProcessorpp = beanFactory.getBean(ppName, BeanPostProcessor.class); nonOrderedPostProcessors.add(pp); if (ppinstanceofMergedBeanDefinitionPostProcessor) { internalPostProcessors.add(pp); } } // 注册无序的 BeanPostProcessorregisterBeanPostProcessors(beanFactory, nonOrderedPostProcessors); // Finally, re-register all internal BeanPostProcessors.sortPostProcessors(internalPostProcessors, beanFactory); // 注册 MergedBeanDefinitionPostProcessorregisterBeanPostProcessors(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).// 添加 ApplicationListenerDetectorbeanFactory.addBeanPostProcessor(newApplicationListenerDetector(applicationContext)); }
- 测试用 Bean
publicclassDemoInstantiationAwareBeanPostProcessorimplementsInstantiationAwareBeanPostProcessor { @OverridepublicObjectpostProcessBeforeInstantiation(Class<?> beanClass, StringbeanName) throwsBeansException { System.out.println("init bean beanClass = " + beanClass.getSimpleName() + " beanName = " + beanName); returnnull; } }
- 按照笔者的注释,可以知道
DemoInstantiationAwareBeanPostProcessor
这个类是一个无序 Bean
- 注册方法信息截图
在org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBean(java.lang.String, org.springframework.beans.factory.support.RootBeanDefinition, java.lang.Object[])
中有如下代码
Objectbean = resolveBeforeInstantiation(beanName, mbdToUse);
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#resolveBeforeInstantiation
@NullableprotectedObjectresolveBeforeInstantiation(StringbeanName, RootBeanDefinitionmbd) { Objectbean = 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) { /** * 主要实现{@link org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation(java.lang.Class, java.lang.String)} */bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName); if (bean != null) { bean = applyBeanPostProcessorsAfterInitialization(bean, beanName); } } } mbd.beforeInstantiationResolved = (bean != null); } returnbean; }
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsBeforeInstantiation
@NullableprotectedObjectapplyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, StringbeanName) { for (BeanPostProcessorbp : getBeanPostProcessors()) { if (bpinstanceofInstantiationAwareBeanPostProcessor) { InstantiationAwareBeanPostProcessoribp = (InstantiationAwareBeanPostProcessor) bp; // 调用自定义实现Objectresult = ibp.postProcessBeforeInstantiation(beanClass, beanName); if (result != null) { returnresult; } } } returnnull; }
这个地方已经可以看到InstantiationAwareBeanPostProcessor
出现了,并且调用了方法postProcessBeforeInstantiation
,此处就可以调用我们的自定义方法了