Spring源码学习11

1.BeanFactoryPostProcessor

/**
 * 允许自定义修改应用程序上下文的bean定义,调整上下文的基础bean工厂的bean属性值。
 *
 * <p>应用程序上下文可以在其bean定义中自动检测BeanFactoryPostProcessor bean
 * ,并在创建任何其他bean之前应用它们。
 *
 * BeanFactoryPostProcessor可以与bean定义交互并修改bean定义,但绝不能与bean实例交互。
 * 这样做可能会导致bean过早实例化,违反容器并导致意外的副作用。 如果需要bean实例交互,
 * 请考虑实现{@link BeanPostProcessor}
 *
 * @author Juergen Hoeller
 * @since 06.07.2003
 * @see BeanPostProcessor
 * @see PropertyResourceConfigurer
 */
public interface BeanFactoryPostProcessor {

	/**
	 * 在标准初始化之后修改应用程序上下文的内部bean工厂。
	 * 将加载所有bean定义,但尚未实例化任何bean。 这允许覆盖或添加属性,甚至是初始化bean。
	 * @param beanFactory the bean factory used by the application context
	 * @throws org.springframework.beans.BeansException in case of errors
	 */
	void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;

}

3.BeanDefinitionRegistryPostProcessor

/**
 * 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.
 *
 * {@link BeanFactoryPostProcessor}扩展接口,在常常规BeanFactoryPostProcessor检测开始之前
 * 允许更多的bean definitions注册<i>before</i>
 * 特别的BeanDefinitionRegistryPostProcessor可以注册更多的bean definitions
 * 而bean定义又定义了BeanFactoryPostProcessor实例
 *
 * @author Juergen Hoeller
 * @since 3.0.1
 * @see org.springframework.context.annotation.ConfigurationClassPostProcessor
 */
public interface BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessor {

	/**
	 * 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
	 */
	void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException;

}

3.分析invokeBeanFactoryPostProcessors(beanFactory);从字面上理解调用注册的BeanFactoryPostProcessor。

首先我们要清楚注册BeanFactoryPostProcessor有两种方式

方式一:配置的方式———编写BeanFactoryPostProcessor接口的实现类,然后配置到*.xml,

方式二:硬编码————AbstractApplicationContext提供了如下方法

@Override
	public void addBeanFactoryPostProcessor(BeanFactoryPostProcessor postProcessor) {
		Assert.notNull(postProcessor, "BeanFactoryPostProcessor must not be null");
		this.beanFactoryPostProcessors.add(postProcessor);
	}

深入到invokeBeanFactoryPostProcessors方法的实现中

public static void invokeBeanFactoryPostProcessors(
			ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {

		// Invoke BeanDefinitionRegistryPostProcessors first, if any.

		//如果有 BeanDefinitionRegistryPostProcessors 的话,调用
		Set<String> processedBeans = new HashSet<String>();
		//beanFactory支持注册bean定义
		if (beanFactory instanceof BeanDefinitionRegistry) {
			BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
			//常规的beanFactoryPostProcessor
			List<BeanFactoryPostProcessor> regularPostProcessors = new LinkedList<BeanFactoryPostProcessor>();
			List<BeanDefinitionRegistryPostProcessor> registryProcessors = new LinkedList<BeanDefinitionRegistryPostProcessor>();

			for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
				//如果为BeanDefinitionRegistryPostProcessor类型
				if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
					BeanDefinitionRegistryPostProcessor registryProcessor =
							(BeanDefinitionRegistryPostProcessor) postProcessor;
					//事先调用下postProcessBeanDefinitionRegistry
					registryProcessor.postProcessBeanDefinitionRegistry(registry);
					//保存下registryPostProcessors
					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.

			//不要在这里初始化FactoryBeans:我们需要保留所有常规bean
			//未初始化让bean工厂的后处理器适用于它们
			//区分BeanDefinitionRegistryPostProcessors为实现PriorityOrdered,Ordered和剩余的接口

			//获取已经注册的postProcessor
			List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<BeanDefinitionRegistryPostProcessor>();

			// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
			//首先,调用实现PriorityOrdered的BeanDefinitionRegistryPostProcessors。这是可能通过xml配置注册的
			String[] postProcessorNames =
					beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
			for (String ppName : postProcessorNames) {
				if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
					currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
					//这些根据类型拿到的bean也需要后置处理,所以暂时保存起来
					processedBeans.add(ppName);
				}
			}
			//排序获取已经注册的postProcessor
			sortPostProcessors(currentRegistryProcessors, beanFactory);
			//registryProcessors添加所有currentRegistryProcessors
			registryProcessors.addAll(currentRegistryProcessors);
			//调用
			invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
			currentRegistryProcessors.clear();

			// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
			// 调用那些实现Ordered的BeanDefinitionRegistryPostProcessors,这是可能通过xml配置注册的
			postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
			for (String ppName : 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.
			// 最后,调用所有其他BeanDefinitionRegistryPostProcessors,直到不再出现其他BeanDefinitionRegistryPostProcessors。
			boolean reiterate = true;
			while (reiterate) {
				reiterate = false;
				postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
				for (String ppName : 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();
			}

			// 现在,调用到目前为止处理的所有处理器的postProcessBeanFactory回调.
			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!

		//不要在这里初始化FactoryBeans:我们需要保留所有未初始化的常规bean,以使bean工厂后处理器适用于它们!
		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.
		sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
		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));
		}
		sortPostProcessors(orderedPostProcessors, beanFactory);
		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);

		// Clear cached merged bean definitions since the post-processors might have
		// modified the original metadata, e.g. replacing placeholders in values...
		beanFactory.clearMetadataCache();
	}

分析上面的代码我们只需要知道几个要点:

  • a.硬件编码的BeanFactoryPostProcessor或者BeanDefinitionRegistryPostProcessor总是先执行,其次才是xml中配置的
  • b.对于硬件编码的BeanFactoryPostProcessor或者BeanDefinitionRegistryPostProcessor是按照添加顺序执行的
  • c.beanFactory实现了BeanDefinitionRegistry接口,则需要先执行BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry;然后是xml中配置的BeanDefinitionRegistryPostProcessors,最后才是BeanFactoryPostProcessor
  • d.BeanDefinitionRegistryPostProcessor的postProcessBeanFactory总是先于BeanFactoryPostProcessor的postProcessBeanFactory执行
  • e.BeanDefinitionRegistryPostProcessor的postProcessBeanFactory优先于BeanFactoryPostProcessor先执行
  • f.执行顺序后置处理会按照有没有实现PriorityOrdered,Ordered的接口判断按照:PriorityOrdered>Ordered>正常的

再去分析代码其实就很简单了

  • 1.beanFactory继承自BeanDefinitionRegistry吗,是的话需要先查找到BeanDefinitionRegistryPostProcessor,先是硬编码进去的执行一次,并保存到一个列表中,用于放到后面执行他的postProcessBeanFactory方法;然后从xml配置中取到BeanDefinitionRegistryPostProcessor,按照先执行实现PriorityOrdered>Ordered>正常的顺序的,调用postProcessBeanDefinitionRegistry方法注册beanDefinition;然后执行BeanDefinitionRegistryPostProcessor类型的BeanFactoryPostProcessor的postProcessBeanFactory然后才是BeanFactoryPostProcessor的后处理器。
  • 2.如果beanFactory没有继承自BeanDefinitionRegistry则执行硬编码方式添加的BeanFactoryPostProcessor
  • 3.从xml配置中查找不包含在1,2两步中已经用过的BeanFactoryPostProcessor,然后按照顺序PriorityOrdered>Ordered>正常的,分别调用下去

4.registerBeanPostProcessors(beanFactory);注册BeanPostProcessors

public static void registerBeanPostProcessors(
			ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
		//从beanFactory中获取BeanPostProcessor类型的beanNames
		String[] 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.
		// BeanPostProcessorChecker记录可能出现某些beanPostProcessors为注册但是bean已经初始化的状况
		// 总数量
		int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
		// 添加一个BeanPostProcessorChecker
		beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

		// Separate between BeanPostProcessors that implement PriorityOrdered,
		// Ordered, and the rest.
		List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanPostProcessor>();
		// 内部的postProcessors 如MergedBeanDefinitionPostProcessor
		List<BeanPostProcessor> internalPostProcessors = new ArrayList<BeanPostProcessor>();
		List<String> orderedPostProcessorNames = new ArrayList<String>();
		List<String> nonOrderedPostProcessorNames = new ArrayList<String>();
		for (String ppName : postProcessorNames) {
			if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
				BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
				priorityOrderedPostProcessors.add(pp);
				if (pp instanceof MergedBeanDefinitionPostProcessor) {
					internalPostProcessors.add(pp);
				}
			}
			else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
				orderedPostProcessorNames.add(ppName);
			}
			else {
				nonOrderedPostProcessorNames.add(ppName);
			}
		}

		// First, register the BeanPostProcessors that implement PriorityOrdered.
		// 按顺序注册优先级最高的beanPostProcessors
		sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
		registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

		// Next, register the BeanPostProcessors that implement Ordered.
		// 按顺序注册实现ordered接口的BeanPostProcessors
		List<BeanPostProcessor> orderedPostProcessors = new ArrayList<BeanPostProcessor>();
		for (String ppName : orderedPostProcessorNames) {
			BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
			orderedPostProcessors.add(pp);
			if (pp instanceof MergedBeanDefinitionPostProcessor) {
				internalPostProcessors.add(pp);
			}
		}
		sortPostProcessors(orderedPostProcessors, beanFactory);
		registerBeanPostProcessors(beanFactory, orderedPostProcessors);

		// Now, register all regular BeanPostProcessors.
		// 注册自然顺序的BeanPostProcessors
		List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<BeanPostProcessor>();
		for (String ppName : nonOrderedPostProcessorNames) {
			BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
			nonOrderedPostProcessors.add(pp);
			if (pp instanceof MergedBeanDefinitionPostProcessor) {
				internalPostProcessors.add(pp);
			}
		}
		registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);

		// Finally, re-register all internal BeanPostProcessors.
		// 最后 注册内部的MergedBeanDefinitionPostProcessor类型的internalPostProcessors
		sortPostProcessors(internalPostProcessors, beanFactory);
		registerBeanPostProcessors(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).
		// 注册用于检测内部bean为ApplicationListeners的ApplicationListenerDetector
		// 将它移动到处理器链的末尾(用于拾取代理等)
		beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
	}
  • a.注册一个BeanPostProcessor,BeanPostProcessorChecker用于记录可能出现某些beanPostProcessors为注册但是bean已经初始化的状况
  • b.按照顺序注册BeanPostProcessor,对于MergedBeanDefinitionPostProcessor类型的保存到集合中
  • c.按照顺序PriorityOrdered>Ordered>正常 顺序挨个注册BeanPostProcessors
  • d.注册MergedBeanDefinitionPostProcessors
  • e.注册检测内部bean为ApplicationListeners的ApplicationListenerDetector 将它移动到处理器链的末尾(用于拾取代理等)

5.ApplicationEventMulticaster

  • a.ApplicationEventMulticaster:管理那些实现{@link ApplicationListener}接口的对象,并且向listener发布事件,相关方法
  • addApplicationListener()添加一个侦听器以通知所有事件、removeApplicationListener()删除一个监听器、removeAllListeners()删除所有的监听器、multicastEvent()广播时间到适当的监听器
  • b.AbstractApplicationEventMulticaster:{@link ApplicationEventMulticaster}接口的抽象实现,提供基本的监听器注册工具,默认情况下不允许出现多个相同的监听器的,因为AbstractApplicationEventMulticaster将 监听器保存到linkedHashSet

6.initApplicationEventMulticaster()

/**
	 * Initialize the ApplicationEventMulticaster.
	 * Uses SimpleApplicationEventMulticaster if none defined in the context.
	 *
	 * 初始化ApplicationEventMulticaster,如果上下文中未定义
	 * 则使用SimpleApplicationEventMulticaster
	 * @see org.springframework.context.event.SimpleApplicationEventMulticaster
	 */
	protected void initApplicationEventMulticaster() {
		//TODO 扩展点,查找beanFactory中是否有applicationEventMulticaster名称的bean,没有的话使用Spring提供的SimpleApplicationEventMulticaster
		ConfigurableListableBeanFactory beanFactory = getBeanFactory();
		if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
			this.applicationEventMulticaster =
					beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
			if (logger.isDebugEnabled()) {
				logger.debug("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
			}
		}
		else {
			this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
			beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
			if (logger.isDebugEnabled()) {
				logger.debug("Unable to locate ApplicationEventMulticaster with name '" +
						APPLICATION_EVENT_MULTICASTER_BEAN_NAME +
						"': using default [" + this.applicationEventMulticaster + "]");
			}
		}
	}

由于ApplicationContext实现了ApplicationEventPublisher接口我们,所以可以通过使用ApplicationContext的publishEvent方法进行消息的发布事件

圈住的地方会获取到我们通过initApplicationEventMulticaster()方法注册的ApplicationEventMulticaster,我们进入Spring给我们提供的默认的SimpleApplicationEventMulticaster.multicastEvent方法

@Override
	public void multicastEvent(final ApplicationEvent event, ResolvableType eventType) {
		ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event));
		for (final ApplicationListener<?> listener : getApplicationListeners(event, type)) {
			Executor executor = getTaskExecutor();
			if (executor != null) {
				executor.execute(new Runnable() {
					@Override
					public void run() {
						invokeListener(listener, event);
					}
				});
			}
			else {
				invokeListener(listener, event);
			}
		}
	}

然后listeners就可以接收到消息了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值