`

spring之BeanDefinitionRegistryPostProcessor接口

阅读更多

//该接口继承自BeanFactoryPostProcessor,该接口可用于动态像spring注册bean
//例如在spring跟mybatis的整合中MapperScannerConfigurer就实现了该类用于动态注册mapper。
public interface BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessor {

	void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException;

}

public interface BeanFactoryPostProcessor {

	void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;

}

//其实现原理为:在spring初始化的时候会执行AbstractApplicationContext中的refresh方法
public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
			// Prepare this context for refreshing.
			prepareRefresh();

			// Tell the subclass to refresh the internal bean factory.
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

			// Prepare the bean factory for use in this context.
			prepareBeanFactory(beanFactory);

			try {
				// Allows post-processing of the bean factory in context subclasses.
				postProcessBeanFactory(beanFactory);

				// Invoke factory processors registered as beans in the context.
				//然后走这里去注册
				invokeBeanFactoryPostProcessors(beanFactory);

				// Register bean processors that intercept bean creation.
				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();
			}

			catch (BeansException ex) {
				// Destroy already created singletons to avoid dangling resources.
				destroyBeans();

				// Reset 'active' flag.
				cancelRefresh(ex);

				// Propagate exception to caller.
				throw ex;
			}
		}
	}


protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
		PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
	}

//最后调PostProcessorRegistrationDelegate中的该方法
public static void invokeBeanFactoryPostProcessors(
			ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {

		// Invoke BeanDefinitionRegistryPostProcessors first, if any.
		Set<String> processedBeans = new HashSet<String>();

		if (beanFactory instanceof BeanDefinitionRegistry) {
			BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
			List<BeanFactoryPostProcessor> regularPostProcessors = new LinkedList<BeanFactoryPostProcessor>();
			List<BeanDefinitionRegistryPostProcessor> registryPostProcessors =
					new LinkedList<BeanDefinitionRegistryPostProcessor>();

			for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
				if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
					BeanDefinitionRegistryPostProcessor registryPostProcessor =
							(BeanDefinitionRegistryPostProcessor) postProcessor;
					registryPostProcessor.postProcessBeanDefinitionRegistry(registry);
					registryPostProcessors.add(registryPostProcessor);
				}
				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.
			String[] postProcessorNames =
					beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);

			// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
			List<BeanDefinitionRegistryPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanDefinitionRegistryPostProcessor>();
			for (String ppName : postProcessorNames) {
				if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
					priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
					processedBeans.add(ppName);
				}
			}
			OrderComparator.sort(priorityOrderedPostProcessors);
			registryPostProcessors.addAll(priorityOrderedPostProcessors);
			invokeBeanDefinitionRegistryPostProcessors(priorityOrderedPostProcessors, registry);

			// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
			postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
			List<BeanDefinitionRegistryPostProcessor> orderedPostProcessors = new ArrayList<BeanDefinitionRegistryPostProcessor>();
			for (String ppName : postProcessorNames) {
				if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
					orderedPostProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
					processedBeans.add(ppName);
				}
			}
			OrderComparator.sort(orderedPostProcessors);
			registryPostProcessors.addAll(orderedPostProcessors);
			invokeBeanDefinitionRegistryPostProcessors(orderedPostProcessors, registry);

			// 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)) {
						BeanDefinitionRegistryPostProcessor pp = beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class);
						registryPostProcessors.add(pp);
						processedBeans.add(ppName);
						//这里执行该方法
						pp.postProcessBeanDefinitionRegistry(registry);
						reiterate = true;
					}
				}
			}

			// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
			invokeBeanFactoryPostProcessors(registryPostProcessors, 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!
		String[] postProcessorNames =
				beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

		// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
		// Ordered, and the rest.
		List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
		List<String> orderedPostProcessorNames = new ArrayList<String>();
		List<String> nonOrderedPostProcessorNames = new ArrayList<String>();
		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.
		OrderComparator.sort(priorityOrderedPostProcessors);
		invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

		// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
		List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
		for (String postProcessorName : orderedPostProcessorNames) {
			orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
		}
		OrderComparator.sort(orderedPostProcessors);
		invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

		// Finally, invoke all other BeanFactoryPostProcessors.
		List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
		for (String postProcessorName : nonOrderedPostProcessorNames) {
			nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
		}
		invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
	}
分享到:
评论

相关推荐

    com-spring-ioc-demo:源码主要是学习Spring IOC的原理,以及对Bean的注册及控制,主要运用以下类对Spring进行扩展学习:BeanPostProcessor,BeanFactoryAware,BeanNameAware,ApplicationContextAware,FactoryBean,BeanDefinitionRegistryPostProcessor,BeanFactoryPostProcessor,BeanPostProcessor,ResourceLoaderA

    com-spring-ioc-demo:源码主要是...注册Bean到Spring容器(BeanDefinitionRegistryPostProcessor接口)4.通过FactoryBean结合InvocationHandler关于动态代理invoke()方法的理解5.BeanNameAware 7.BeanFactoryPostPro

    详解Spring中实现接口动态的解决方法

    这可以通过Spring的BeanDefinitionRegistryPostProcessor实现。在这个处理器中,我们可以遍历所有注册的BeanDefinition,找到带有特定注解的接口,并为其生成动态实现。这个过程中,可能需要解析注解的内容,例如...

    自定义注解得使用,模拟spring通过注解方式创建bean实例

    Spring使用BeanDefinitionRegistryPostProcessor接口来注册bean定义。在我们的例子中,我们可以创建一个类实现此接口,并在其中扫描带有`MyComponent`注解的类: ```java import org.springframework.beans.factory...

    Spring源码解析文件说明

    Spring框架作为Java领域内最流行的轻量级框架之一,其核心是依赖注入(Dependency Injection, DI)和面向切面编程(Aspect Oriented Programming, AOP)。在本文中,我们将详细探讨Spring框架中的IOC容器启动过程,...

    Spring笔记(第九次)1

    通过实现BeanDefinitionRegistryPostProcessor接口,可以利用postProcessBeanDefinitionRegistry方法来注册新的bean定义或者修改现有的bean定义。这样可以实现更灵活的配置管理,比如动态插入bean定义。 Spring容器...

    spring扩展原理1

    本文主要探讨Spring扩展原理,特别是`BeanFactoryPostProcessor`、`BeanDefinitionRegistryPostProcessor`以及`ApplicationListener`这三种核心扩展点。 首先,`BeanFactoryPostProcessor`是Spring IOC容器中的一种...

    spring加载

    Spring加载机制还支持自定义加载逻辑,比如通过实现`BeanDefinitionRegistryPostProcessor`接口,可以在bean定义注册后,bean实例化之前进行自定义处理。 以上就是关于“spring加载”的主要知识点,涵盖了Spring...

    Spring bean对象实例化实现过程图解

    Spring Bean 对象实例化实现过程图解...Spring Bean 对象实例化实现过程图解是一个复杂的过程,需要了解 BeanDefinitionRegistryPostProcessor 接口、BeanPostProcessor 的注册、getSingleton 方法、createBean 方法和 ...

    这一次搞懂Spring自定义标签以及注解解析原理说明.docx

    在Spring框架中,自定义标签和注解解析是核心功能之一,它们允许开发者根据特定需求扩展和定制Spring的配置方式。本文将深入探讨这两个概念的解析原理,帮助读者理解Spring如何处理自定义标签和注解。 首先,让我们...

    关于mybatis spring与dubbo是怎么通过一个接口 你就能调用到一个bean方法的讲解

    在Spring、MyBatis和Dubbo等框架中,实现通过接口调用具体bean的方法主要依赖于Spring的IoC(Inversion of Control,控制反转)和AOP(Aspect Oriented Programming,面向切面编程)机制。这里我们将深入探讨如何在...

    Spring Aop 源码流程.doc

    当Spring容器实例化Bean时,`InstantiationAwareBeanPostProcessor`接口的实现会被调用,如`AspectJAwareAdvisorAutoProxyCreator`,它会在合适的时机识别出带有切面注解的Bean,并为它们创建代理。代理的创建过程...

    Spring源码深度解析与注解驱动开发1

    3. `ApplicationListener`:实现该接口的类可以监听到Spring应用上下文中的事件,比如bean初始化、销毁等,从而做出响应。 三、Web相关 1. Servlet 3.0:Spring与Servlet容器紧密集成,支持Servlet 3.0特性,如...

    spring原理1

    1. 实现了`PriorityOrdered`接口的`BeanDefinitionRegistryPostProcessor`先执行,它们具有最高的优先级。 2. 然后是实现了`Ordered`接口的`BeanDefinitionRegistryPostProcessor`,按照指定的顺序执行。 3. 最后,...

    Springboot启动扩展点详细总结.docx

    BeanDefinitionRegistryPostProcessor 接口用于在 Spring 加载 Bean 定义后但实例化 Bean 之前执行。这为动态注册额外的 Bean 提供了机会,甚至可以从类路径之外加载 Bean。实现该接口并覆盖 ...

    spring源码学习

    ### Spring源码学习知识点 ...综上所述,Spring的BeanDefinition和实例化Bean的过程是其核心机制之一,涉及到复杂的类和接口交互。深入理解这些机制有助于更好地掌握Spring框架的工作原理和技术要点。

    详解Spring Boot 使用Java代码创建Bean并注册到Spring中

    同时,Spring会识别出那些实现了BeanDefinitionRegistryPostProcessor接口的类,例如`ConfigurationClassPostProcessor`,并在实例化用户定义的Bean之前调用它们的`postProcessBeanDefinitionRegistry`方法。...

    Spring注解驱动扩展原理BeanFactoryPostProcessor

    在上面的代码中,我们创建了一个MyBeanDefinitionRegistryPostProcessor类,该类实现了BeanDefinitionRegistryPostProcessor接口。在postProcessBeanDefinitionRegistry方法中,我们可以对Bean定义信息进行修改或...

    详解Spring中Bean的加载的方法

    在Spring中,Bean的动态加载是指在运行时根据需求加载特定的Bean,这通常通过实现`BeanFactoryPostProcessor`和`BeanDefinitionRegistryPostProcessor`接口来实现。这些接口允许开发者在容器启动时修改Bean定义或...

    Spring-cloud Feign 的深入理解

    Spring Cloud Feign 提供了一个声明式的 REST 客户端,帮助开发者快速构建 RESTful 风格的微服务接口。其核心组件包括 Feign 客户端、Feign 配置、FeignClientsRegistrar、FeignClientFactoryBean、FeignContext、...

Global site tag (gtag.js) - Google Analytics