Spring BeanPostProcessor : ErrorPageRegistrarBeanPostProcessor

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/andy_zhang2007/article/details/86373024

概述

BeanPostProcessor检测bean ErrorPageRegistry的创建,检测到时,在它初始化前,获取容器中所有的ErrorPageRegistrar bean,将它们注册到bean ErrorPageRegistry。这是一个针对Springboot Servlet Web应用的BeanPostProcessor,仅在Springboot Servlet Web应用中被应用。

源代码解析

package org.springframework.boot.web.server;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.util.Assert;

/**
 *
 * @author Phillip Webb
 * @author Stephane Nicoll
 * @since 2.0.0
 */
public class ErrorPageRegistrarBeanPostProcessor
		implements BeanPostProcessor, BeanFactoryAware {

	private ListableBeanFactory beanFactory;

	private List<ErrorPageRegistrar> registrars;

	// BeanFactoryAware  定义的方法
	@Override
	public void setBeanFactory(BeanFactory beanFactory) {
		Assert.isInstanceOf(ListableBeanFactory.class, beanFactory,
				"ErrorPageRegistrarBeanPostProcessor can only be used "
						+ "with a ListableBeanFactory");
		this.beanFactory = (ListableBeanFactory) beanFactory;
	}

	// BeanPostProcessor 接口定义的方法,在每个bean创建时,初始化之前对bean应用
	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName)
			throws BeansException {
		if (bean instanceof ErrorPageRegistry) {
			// 检测到正在创建的 bean 是 ErrorPageRegistry,
			// 从容器中找到所有的 ErrorPageRegistrar bean 注册到
			// 该 bean ErrorPageRegistry
			postProcessBeforeInitialization((ErrorPageRegistry) bean);
		}
		return bean;
	}

	// BeanPostProcessor 接口定义的方法,在每个bean创建时,初始化之后对bean应用
	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName)
			throws BeansException {
		// 什么都不做,直接返回bean自身	
		return bean;
	}

	// 从容器中找到所有的 ErrorPageRegistrar bean 注册到 ErrorPageRegistry registry 
	private void postProcessBeforeInitialization(ErrorPageRegistry registry) {
		for (ErrorPageRegistrar registrar : getRegistrars()) {
			registrar.registerErrorPages(registry);
		}
	}

	// 从容器中找到所有的 ErrorPageRegistrar bean,根据bean类型查找
	private Collection<ErrorPageRegistrar> getRegistrars() {
		if (this.registrars == null) {
			// Look up does not include the parent context
			this.registrars = new ArrayList<>(this.beanFactory
					.getBeansOfType(ErrorPageRegistrar.class, false, false).values());
			this.registrars.sort(AnnotationAwareOrderComparator.INSTANCE);
			this.registrars = Collections.unmodifiableList(this.registrars);
		}
		return this.registrars;
	}

}

猜你喜欢

转载自blog.csdn.net/andy_zhang2007/article/details/86373024