ApplicationContext

1. 简介

1.1 类图结构

ApplicationContext类不仅仅包含了BeanFactory的功能,还扩展了许多其他功能,因此通常我们优先使用ApplicationContext类。
image

通常情况下,ApplicationContext下的抽象类图结构如下:
image

1.2 方法执行流

AbstractApplicationContext类抽象了整个容器的所有流程,具体的加载操作则由具体实现类实现:
image

@Override
public void refresh() throws BeansException, IllegalStateException {
	synchronized (this.startupShutdownMonitor) {
	    // 准备上下文环境
		prepareRefresh();
		// 初始化BeanFactory,并读取XML
		ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
		// 对BeanFactory进行各种功能填充
		prepareBeanFactory(beanFactory);
		try {
		    // 子类覆盖方法做额外的处理
			postProcessBeanFactory(beanFactory);
			// 激活BeanFactory的处理器
			invokeBeanFactoryPostProcessors(beanFactory);
			// 注册拦截Bean创建的Bean的处理器
			registerBeanPostProcessors(beanFactory);
			// 为上下文初始化Message源,即不同语言的消息体,国际化处理
			initMessageSource();
			// 初始化应用消息广播器,并放入"applicationEventMulticaster"的Bean中
			initApplicationEventMulticaster();
			// 留给子类来初始化其他的Bean
			onRefresh();
			// 在所有注册的Bean中查找Listener Bean,注册到消息广播器中
			registerListeners();
			// 初始化剩下的单实例
			finishBeanFactoryInitialization(beanFactory);
			// 完成刷新过程,通知生命周期处理器lifecycleProcessor刷新过程,同时发出ContextRefreshEvent进行通知
			finishRefresh();
		} catch (BeansException ex) { /*省略*/
		} finally {
			resetCommonCaches();
		}
	}
}

2 模块详解

2.1 准备上下文环境

prepareRefresh()方法主要是做准备工作,如对系统属性及环境变量的初始化及验证:

  • initPropertySources()
    用户可以根据自身的需要进行重写,并且在方法中进行个性化的属性处理和设置。
  • validateRequiredProperties()
    对属性进行校验
protected void prepareRefresh() {
	this.startupDate = System.currentTimeMillis();
	this.closed.set(false);
	this.active.set(true);

	// Initialize any placeholder property sources in the context environment
	initPropertySources();

	// Validate that all properties marked as required are resolvable
	// see ConfigurablePropertyResolver#setRequiredProperties
	getEnvironment().validateRequiredProperties();

	// Allow for the collection of early ApplicationEvents,
	// to be published once the multicaster is available...
	this.earlyApplicationEvents = new LinkedHashSet<ApplicationEvent>();
}

示例

假设需求:工厂在运行过程中用到的某个设置(例如VAR)是从环境变量中取得的,若用户没有在环境中配置该参数,就不可能运行。

public class MyApplicationContext extends ClassPathXmlApplicationContext {
    public MyApplicationContext(String... configLocation) {
        supert(configLocation);
    }
    /* 在该方法中添加个性化需求,在validateRequiredProperties()进行校验时
    若没有检测到VAR的环境变量,则会抛出异常 */
    protected void initPropertySources() {
        getEnvironment().setRequiredProperties("VAR");
    }
}

2.2 加载BeanFactory

注意,此处获取的BeanFactory对象是DefaultListableBeanFactory
image

protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
    // 初始化BeanFactory,读取、加载、注册XML文件
	refreshBeanFactory();
	// 获取BeanFactory
	ConfigurableListableBeanFactory beanFactory = getBeanFactory();
	return beanFactory;
}

protected final void refreshBeanFactory() throws BeansException {
	if (hasBeanFactory()) {
		destroyBeans();
		closeBeanFactory();
	}
	try {
		DefaultListableBeanFactory beanFactory = createBeanFactory();
		beanFactory.setSerializationId(getId());
		// 是否允许覆盖同名称的不同定义的对象;循环依赖
		customizeBeanFactory(beanFactory);
		loadBeanDefinitions(beanFactory);
		synchronized (this.beanFactoryMonitor) {
			this.beanFactory = beanFactory;
		}
	} catch (IOException ex) { /* */ }
}
// 可自定义实现该方法
protected void customizeBeanFactory(DefaultListableBeanFactory beanFactory) {
	if (this.allowBeanDefinitionOverriding != null) {
		beanFactory.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
	}
	if (this.allowCircularReferences != null) {
		beanFactory.setAllowCircularReferences(this.allowCircularReferences);
	}
}

2.3 扩展BeanFactory

prepareBeanFactory()方法对BeanFactory进行了如下方面的扩展:

  • 增加SPEL语言的支持
  • 增加对属性编辑器的支持
  • 添加ApplicationContextAwareProcessor处理器

    ApplicationContextAware
    EnvironmentAware
    EmbeddedValueResolverAware
    ResourceLoaderAware
    ApplicationEventPublisherAware
    MessageSourceAware

  • 设置可忽略的接口

    EnvironmentAware
    ApplicationContextAware
    ResourceLoaderAware
    ApplicationEventPublisherAware
    MessageSourceAware

  • 增加一些固定的依赖属性

    BeanFactory
    ResourceLoader
    ApplicationEventPublisher
    ApplicationContext

  • 增加AOP的支持
  • 将相关环境变量以及属性注册以单例模式注册
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
    beanFactory.setBeanClassLoader(getClassLoader());
    // 设置beanFactory的表达式语言处理器:SPEL
	beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
	// 为beanFactory增加一个默认的propertyEditor
	beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
	// 设置Aware的后置处理器
	beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
	// 设置几个忽略自动装配的接口
	beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
	beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
	beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
	beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
	beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
    // 设置几个自动装配的特殊规则
	beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
	beanFactory.registerResolvableDependency(ResourceLoader.class, this);
	beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
	beanFactory.registerResolvableDependency(ApplicationContext.class, this);
    // 增加AspectJ的支持
	if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
		beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
		beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
	}

	if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
		beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
	}
	if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
		beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
	}
	if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
		beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
	}
}

2.3.1 SPEL语言的支持

SPEL语言使用#{...}作为界定符。

beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));

Spring使用AbstractAutowireCapableBeanFactory#applyPropertyValue()在Bean的初始化中,对Bean属性进行填充。填充过程使用BeanDefinitionValueResolver#resolveValueIfNecessary()方法对属性值进行解析。

对于一些属性值的类型,会使用beanFactory#evaluateBeanDefinitionString()解析,该方法如下:

  • 判断beanFactory是否存在语言解析器
  • 若存在解析器,使用解析器解析属性值
protected Object evaluateBeanDefinitionString(String value, BeanDefinition beanDefinition) {
	if (this.beanExpressionResolver == null) {
		return value;
	}
	Scope scope = (beanDefinition != null ? getRegisteredScope(beanDefinition.getScope()) : null);
	return this.beanExpressionResolver.evaluate(value, new BeanExpressionContext(this, scope));
}

2.3.2 增加属性注册编辑器

属性注册器接口由PropertyEditorRegistrar实现,该接口的目的是将属性编辑器PropertyEditor注册到Spring中。

public interface PropertyEditorRegistrar {
	void registerCustomEditors(PropertyEditorRegistry registry);
}

PropertyEditor属性编辑器的目的用于将:配置中定义的String类型,转换成对应的Object类型并进行赋值:

例如:ClassEditor属性编辑器,一旦某个实体Bean中存在一些Class类型的属性,那么Spring就会调用ClassEditor将配置中定义的String类型转为Class类型,并进行赋值

ResourceEditorRegistrar类的实现为例,如下:

public void registerCustomEditors(PropertyEditorRegistry registry) {
    ResourceEditor baseEditor = new ResourceEditor(this.resourceLoader, this.propertyResolver);
	doRegisterEditor(registry, Resource.class, baseEditor);
	doRegisterEditor(registry, ContextResource.class, baseEditor);
	doRegisterEditor(registry, InputStream.class, new InputStreamEditor(baseEditor));
	doRegisterEditor(registry, InputSource.class, new InputSourceEditor(baseEditor));
	doRegisterEditor(registry, File.class, new FileEditor(baseEditor));
	// ...

这里向BeanFactory中增加了ResourceEditorRegistrar属性注册器,该属性注册器针对Spring中的大多数属性类型进行了处理:

beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
// AbstractBeanFactory类内容如下
public void addPropertyEditorRegistrar(PropertyEditorRegistrar registrar) {
	this.propertyEditorRegistrars.add(registrar);
}

AbstractBeanFactory#initBeanWrapper()方法将BeanDefinition转换成BeanWrapper的过程中,会调用AbstractBeanFactory中所有的PropertyEditorRegistrar对象。内容如下:

protected void initBeanWrapper(BeanWrapper bw) {
	bw.setConversionService(getConversionService());
	registerCustomEditors(bw);
}
protected void registerCustomEditors(PropertyEditorRegistry registry) {
	PropertyEditorRegistrySupport registrySupport = (registry instanceof PropertyEditorRegistrySupport ? (PropertyEditorRegistrySupport) registry : null);
	if (registrySupport != null) {
		registrySupport.useConfigValueEditors();
	}
	if (!this.propertyEditorRegistrars.isEmpty()) {
		for (PropertyEditorRegistrar registrar : this.propertyEditorRegistrars) {
			try {
				registrar.registerCustomEditors(registry);
			} catch (BeanCreationException ex) { 	/* */ }
		}
	}
	if (!this.customEditors.isEmpty()) {
		for (Map.Entry<Class<?>, Class<? extends PropertyEditor>> entry : this.customEditors.entrySet()) {
			Class<?> requiredType = entry.getKey();
			Class<? extends PropertyEditor> editorClass = entry.getValue();
			registry.registerCustomEditor(requiredType, BeanUtils.instantiateClass(editorClass));
		}
	}
}

示例自定义实现Date类型转换器:
1.定义属性编辑器

public class MyDatePropertyEditorRegistrar implements PropertyEditorRegistrar {
    public void registerCustomEditors(PropertyEditorRegistry registry) {
        // Spring中有现成实现
        CustomDateEditor customerDate = new CustomDateEditor(new SimpleDateFormate("yyyy-MM-dd"), true);
        registry.registerCustomerEditor(Date.class, customerDate);
    }
}

public class CustomDateEditor extends PropertyEditorSupport {
	private final DateFormat dateFormat;
	private final boolean allowEmpty;
	private final int exactDateLength;

	public CustomDateEditor(DateFormat dateFormat, boolean allowEmpty) {
		this.dateFormat = dateFormat;
		this.allowEmpty = allowEmpty;
		this.exactDateLength = -1;
	}

	public CustomDateEditor(DateFormat dateFormat, boolean allowEmpty, int exactDateLength) {
		this.dateFormat = dateFormat;
		this.allowEmpty = allowEmpty;
		this.exactDateLength = exactDateLength;
	}

	@Override
	public void setAsText(String text) throws IllegalArgumentException {
		if (this.allowEmpty && !StringUtils.hasText(text)) {
			setValue(null);
		} else if (text != null && this.exactDateLength >= 0 && text.length() != this.exactDateLength) {
			throw new IllegalArgumentException("Could not parse date: it is not exactly" + this.exactDateLength + "characters long");
		} else {
			try {
				setValue(this.dateFormat.parse(text));
			} catch (ParseException ex) { 	/*  */ 	}
		}
	}

	@Override
	public String getAsText() {
		Date value = (Date) getValue();
		return (value != null ? this.dateFormat.format(value) : "");
	}

}

2.注册到Spring

将自定义的MyDatePropertyEditorRegistrar注册到Spring容器中:

<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
    <property name="propertyEditorRegistrars">
        <list>
            <bean class="com.test.MyDatePropertyEditorRegistrar" />
        </list>
    </property>
</bean>

之所以使用CustomEditorConfigurer类,原因在于该类在Spring中是BeanFactoryPostProcessor,如下内容:

public class CustomEditorConfigurer implements BeanFactoryPostProcessor, Ordered {

	private int order = Ordered.LOWEST_PRECEDENCE;  // default: same as non-Ordered
	private PropertyEditorRegistrar[] propertyEditorRegistrars;
	private Map<Class<?>, Class<? extends PropertyEditor>> customEditors;

	public void setOrder(int order) {
		this.order = order;
	}
	@Override
	public int getOrder() {
		return this.order;
	}
	public void setPropertyEditorRegistrars(PropertyEditorRegistrar[] propertyEditorRegistrars) {
		this.propertyEditorRegistrars = propertyEditorRegistrars;
	}
	public void setCustomEditors(Map<Class<?>, Class<? extends PropertyEditor>> customEditors) {
		this.customEditors = customEditors;
	}


	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
		if (this.propertyEditorRegistrars != null) {
			for (PropertyEditorRegistrar propertyEditorRegistrar : this.propertyEditorRegistrars) {
				beanFactory.addPropertyEditorRegistrar(propertyEditorRegistrar);
			}
		}
		if (this.customEditors != null) {
			for (Map.Entry<Class<?>, Class<? extends PropertyEditor>> entry : this.customEditors.entrySet()) {
				Class<?> requiredType = entry.getKey();
				Class<? extends PropertyEditor> propertyEditorClass = entry.getValue();
				beanFactory.registerCustomEditor(requiredType, propertyEditorClass);
			}
		}
	}
}

2.3 BeanFactory的后置处理器

Spring中提供的后置处理器分为2类:

  • BeanFactoryPostProcessor:作用域是容器级别。容器在实例化任何Bean之前操作
  • BeanPostProcessor:作用域是Bean对象级别。容器在实例化Bean动作时的操作

2.3.1 BeanFactoryPostProcessor简介

简介

典型应用:PropertyPlaceholderConfigurer,如下使用:

<bean id="mesHandler" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>config/bean.properties</value>
        </list>
    </property>
</bean>
<bean id="message" class="com.test.HelloMessage">
    <property name="mes">
        <value>${user.message}</value>
    </property>
</bean>

2.3.2 BeanFactoryPostProcessor使用

AbstractApplicationContext中使用BeanFactoryPostProcessor的方式如下:

public void refresh() throws BeansException, IllegalStateException {
    // 执行BeanFactory中的所有BeanFactoryPostProcessor
    invokeBeanFactoryPostProcessors(beanFactory);
}

protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
	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(new LoadTimeWeaverAwareProcessor(beanFactory));
		beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
	}
}

执行BeanFactoryPostProcessor委托给了PostProcessorRegistrationDelegate类来实现。
对于BeanFactoryPostProcessor的处理分为2种情况:

  • 特殊的BeanDefinitionRegistryPostProcessor
  • 常规的BeanFactoryPostProcessor

无论是哪种情况,都需要考虑两种情况:

  • 硬编码注册后置处理器

    硬编码注册的后处理器主要通过:AbstractApplicationContext#addBeanFactoryPostProcessor()

  • 通过配置注入的后置处理器
public static void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {

	Set<String> processedBeans = new HashSet<String>();
	if (beanFactory instanceof BeanDefinitionRegistry) {
		BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
		// 记录通过硬编码方式注册的BeanFactoryPostProcessor
		List<BeanFactoryPostProcessor> regularPostProcessors = new LinkedList<BeanFactoryPostProcessor>();
		// 记录通过硬编码方式注册的BeanDefinitionRegistryPostProcessor
		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);
			}
		}
		// 获取所有通过配置文件注入的BeanDefinitionRegistryPostProcessor类
		String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
		
		// 1.执行实现PriorityOrdered的所有BeanDefinitionRegistryPostProcessor
		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);
			}
		}
		sortPostProcessors(beanFactory, priorityOrderedPostProcessors);
		registryPostProcessors.addAll(priorityOrderedPostProcessors);
		invokeBeanDefinitionRegistryPostProcessors(priorityOrderedPostProcessors, registry);
        // 2.执行实现Ordered的所有BeanDefinitionRegistryPostProcessor
		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);
			}
		}
		sortPostProcessors(beanFactory, orderedPostProcessors);
		registryPostProcessors.addAll(orderedPostProcessors);
		invokeBeanDefinitionRegistryPostProcessors(orderedPostProcessors, registry);
        // 3.执行其他所有的BeanDefinitionRegistryPostProcessor
		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;
				}
			}
		}
		invokeBeanFactoryPostProcessors(registryPostProcessors, beanFactory);
		invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
	} else {
		invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
	}

    // 获取所有配置注入的BeanFactoryPostProcessor,并执行
	String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
	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);
		}
	}
	sortPostProcessors(beanFactory, priorityOrderedPostProcessors);
	invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
	List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
	for (String postProcessorName : orderedPostProcessorNames) {
		orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
	}
	sortPostProcessors(beanFactory, orderedPostProcessors);
	invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
	List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
	for (String postProcessorName : nonOrderedPostProcessorNames) {
		nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
	}
	invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);

	beanFactory.clearMetadataCache();
}

2.4 BeanPostFactory

注册BeanPostFactory,注意这里只是注册,真正的调用在getBean()方法中。

protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
	PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
}
 
// -- PostProcessorRegistrationDelegate
public static void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
    // 获取所有的BeanPostProcessor
	String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
	int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
	beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
    // 各种类型的BeanPostProcessor集合
	List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanPostProcessor>();
	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);
		}
	}
    // 1. 注册实现了PriorityOrdered的BeanPostProcessors
	sortPostProcessors(beanFactory, priorityOrderedPostProcessors);
	registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
    // 2. 注册实现了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(beanFactory, orderedPostProcessors);
	registerBeanPostProcessors(beanFactory, orderedPostProcessors);
	// 3. 注册所有通用的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);
	// 4. 注册所有的internalPostProcessors
	sortPostProcessors(beanFactory, internalPostProcessors);
	registerBeanPostProcessors(beanFactory, internalPostProcessors);
	beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}

2.5 事件监听器

初始化事件监听器:

  • 若用户自定义了事件广播器:使用用户自定义的时间广播器
  • 若用户未定义了事件广播器:使用SimpleApplicationEventMulticaster
protected void initApplicationEventMulticaster() {
	ConfigurableListableBeanFactory beanFactory = getBeanFactory();
	if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
		this.applicationEventMulticaster = beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
	} else {
		this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
		beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
	}
}

2.5.1 注册发布监听器

该代码分为2步骤:

  1. 注册监听器也会有2种方式:
    • 硬编码监听器
    • 配置方式实现的监听器
  2. 发布早期的事件:初始化非惰性的单例前(即我们通常使用的所有Bean)

代码如下所示:

protected void registerListeners() {
	// Register statically specified listeners first.
	for (ApplicationListener<?> listener : getApplicationListeners()) {
		getApplicationEventMulticaster().addApplicationListener(listener);
	}
	// Do not initialize FactoryBeans here: We need to leave all regular beans
	// uninitialized to let post-processors apply to them!
	String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
	for (String listenerBeanName : listenerBeanNames) {
		getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
	}
	// Publish early application events now that we finally have a multicaster...
	Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
	this.earlyApplicationEvents = null;
	if (earlyEventsToProcess != null) {
		for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
			getApplicationEventMulticaster().multicastEvent(earlyEvent);
		}
	}
}

2.5.2 广播器的默认实现

广播事件的代码如下所示:

public void multicastEvent(ApplicationEvent event) {
	multicastEvent(event, resolveDefaultEventType(event));
}

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);
		}
	}
}

// 所有的异常都会被捕获,而不会抛出。
protected void invokeListener(ApplicationListener listener, ApplicationEvent event) {
	ErrorHandler errorHandler = getErrorHandler();
	if (errorHandler != null) {
		try {
			listener.onApplicationEvent(event);
		} catch (Throwable err) { /* */ }
	} else {
		try {
			listener.onApplicationEvent(event);
		} catch (ClassCastException ex) {/*  */ }
	}
}
posted @ 2019-03-11 10:17  wolf_w  阅读(298)  评论(0编辑  收藏  举报