一、概述
1.Spring Context概念
创建上下文并将BeanPostProcessor加载到spring
2.Spring Application Context概念
Spring通过应用上下文(Application Context)装载bean的定义并把它们组装起来。Spring应用上下文全权负责对象的创建和组装。
3. 关系
(1)Spring Context 模块核心是Spring Context
(2)Spring Context 核心是Spring Application Context
(3)Spring Application Context 的核心方法是 AbstractApplicationContext
二、AbstractApplicationContext之刷新源码分析
1. 基础源码
高效记忆:Spring应用文刷新 — 刷机
(1)手机系统太卡了于是自己刷机。首先 准备刷机环境 (准备刷新上下文环境),准备好后老系统 初始化并加载 定义信息(初始化beanfactory,并加载bean deFinitions信息)
(2)然后进行系统 配置 并(对beanFacotry进行配置)开始系统 激活 并提交过程(激活beanfactoryPostProcessors)
(3)再进行验证码 注册 并提交过程(注册BeanPostProcessors),注册后新系统 初始化信息资源、广播 且注册监听器(初始化MessageSource、初始化事件广播器、注册事件监听器)
(4)最后系统 热加载弹粒 并(构造热加载单例bean)完成刷机 (完成刷新过程,通知生命周期处理器),如果刷机 错误 就 销户并修改 激活标识(销毁bean、修改active标识)
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
prepareRefresh(); // #1 准备刷新上下文环境
// Tell the subclass to refresh the internal bean factory.
ConfigurableListablebeanfactory beanfactory = obtainFreshbeanfactory(); // #2 初始化beanfactory,并加载bean deFinitions信息
// Prepare the bean factory for use in this context.
preparebeanfactory(beanfactory); // #3 对beanFacotry进行配置
try {
// Allows post-processing of the bean factory in context subclasses.
postProcessbeanfactory(beanfactory); // #4 提供给子类扩展的预留方法
// Invoke factory processors registered as beans in the context.
invokebeanfactoryPostProcessors(beanfactory); // #5 激活beanfactoryPostProcessors
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanfactory); // #6 注册BeanPostProcessors
// Initialize message source for this context.
initMessageSource(); // #7 初始化MessageSource
// Initialize event multicaster for this context.
initApplicationEventMulticaster(); // #8 初始化事件广播器
// Initialize other special beans in specific context subclasses.
onRefresh(); // #9 提供给子类初始化其他的Bean
// Check for listener beans and register them.
registerListeners(); // #10 注册事件监听器
// Instantiate all remaining (non-lazy-init) singletons.
finishbeanfactoryInitialization(beanfactory); // #11 构造热加载单例bean
// Last step: publish corresponding event.
finishRefresh(); // #12 完成刷新过程,通知生命周期处理器
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// Destroy already created singletons to avoid dangling resources.
destroyBeans(); // #13 出错了,销毁bean
// Reset 'active' flag.
cancelRefresh(ex); // #14 出错了,修改active标识
// Propagate exception to caller.
throw ex;
}
finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need Metadata for singleton beans anymore...
resetCommonCaches();
}
}
}
2.初始化并加载 obtainFreshbeanfactory
AbstractApplicationContext—obtainFreshbeanfactory ----> AbstractRefreshableApplicationContext—refreshbeanfactory
protected final void refreshbeanfactory() throws BeansException {
if (hasbeanfactory()) { // #1 如果已存在beanfactory,销毁原来的beanfactory
destroyBeans();
closebeanfactory();
}
try {
DefaultListablebeanfactory beanfactory = createbeanfactory(); // #2 创建DefaultListablebeanfactory
beanfactory.setSerializationId(getId());
customizebeanfactory(beanfactory);
// #3 加载bean deFinitions信息,loadBeanDeFinitions是抽象方法,不同实现类会从不同的配置中获取bean deFinitions信息,
// 如AnnotationConfigWebApplicationContext,XmlWebApplicationContext。
loadBeanDeFinitions(beanfactory);
synchronized (this.beanfactoryMonitor) {
this.beanfactory = beanfactory;
}
}
catch (IOException ex) {
throw new ApplicationContextException("I/O error parsing bean deFinition source for " + getdisplayName(), ex);
}
}
3.激活 beanfactoryPostProcessors
(1)beanfactoryPostProcessor是spring提供的扩展接口,可以通过beanfactoryPostProcessor对beanfactory进行自定义处理,如修改其他BeanDeFinition的配置。
(2)beanfactoryPostProcessor可以调整beanfactory,甚至修改BeanDeFinition,如CustomEditorConfigurer,将用户定义的propertyeditor注册到beanfactory中,以便后续使用。
(3)BeanDeFinitionRegistryPostProcessor可以注册新的BeanDeFinition,如ConfigurationClasspostProcessor,是实现springboot很关键的类
AbstractApplicationContext—invokebeanfactoryPostProcessors ----> PostProcessorRegistrationDelegate—invokebeanfactoryPostProcessors
public static void invokebeanfactoryPostProcessors(
ConfigurableListablebeanfactory beanfactory, List<beanfactoryPostProcessor> beanfactoryPostProcessors) {
Set<String> processedBeans = new HashSet<String>();
// #1 如果beanfactory是BeanDeFinitionRegistry,需要处理beanfactoryPostProcessors,
// BeanDeFinitionRegistryPostProcessor,否则只处理beanfactoryPostProcessors
if (beanfactory instanceof BeanDeFinitionRegistry) {
BeanDeFinitionRegistry registry = (BeanDeFinitionRegistry) beanfactory;
List<beanfactoryPostProcessor> regularPostProcessors = new LinkedList<beanfactoryPostProcessor>();
List<BeanDeFinitionRegistryPostProcessor> registryPostProcessors =
new LinkedList<BeanDeFinitionRegistryPostProcessor>();
// #2 方法参数beanfactoryPostProcessors是AbstractApplicationContext---beanfactoryPostProcessors属性,
// 用户可以通过AbstractApplicationContext---addbeanfactoryPostProcessor方法添加beanfactoryPostProcessor。这里对beanfactoryPostProcessors参数进行分类
for (beanfactoryPostProcessor postProcessor : beanfactoryPostProcessors) { if (postProcessor instanceof BeanDeFinitionRegistryPostProcessor) {
BeanDeFinitionRegistryPostProcessor registryPostProcessor =
(BeanDeFinitionRegistryPostProcessor) postProcessor;
registryPostProcessor.postProcessBeanDeFinitionRegistry(registry);
registryPostProcessors.add(registryPostProcessor);
}
else {
regularPostProcessors.add(postProcessor);
}
}
// #3 获取beanfactory已经存在的BeanDeFinitionRegistryPostProcessor,这里并没有直接构建BeanDeFinitionRegistryPostProcessor,而且通过beanName获取
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));
// #4 获取实现了PriorityOrdered接口的BeanDeFinitionRegistryPostProcessor,添加到priorityOrderedPostProcessors
processedBeans.add(ppName);
}
}
// #5 对priorityOrderedPostProcessors排序
sortPostProcessors(beanfactory, priorityOrderedPostProcessors);
// #6 排序结果添加到registryPostProcessors
registryPostProcessors.addAll(priorityOrderedPostProcessors);
// #7 调用BeanDeFinitionRegistryPostProcessor#postProcessBeanDeFinitionRegistry
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) {
// #8 处理实现了Ordered的BeanDeFinitionRegistryPostProcessor
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);
// 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) {
// #9 处理剩余的BeanDeFinitionRegistryPostProcessor
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);
}
...
}
4.初始化事件广播 initApplicationEventMulticaster
4.1 Spring事件体系包括三个组件:
ApplicationEvent事件,ApplicationListener事件监听器,ApplicationEventMulticaster事件广播器。
4.2 事件广播器负责管理事件监听器,并将事件广播给监听器。
AbstractApplicationContext — initApplicationEventMulticaster
rotected void initApplicationEventMulticaster() {
ConfigurableListablebeanfactory beanfactory = getbeanfactory();
if (beanfactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
this.applicationEventMulticaster =
beanfactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class); //#1 使用用户定义的事件广播器
if (logger.isDebugEnabled()) {
logger.debug("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
}
}
else {
this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanfactory);
beanfactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster); //#2 使用默认的事件广播器
if (logger.isDebugEnabled()) {
logger.debug("Unable to locate ApplicationEventMulticaster with name '" +
APPLICATION_EVENT_MULTICASTER_BEAN_NAME +
"': using default [" + this.applicationEventMulticaster + "]");
}
}
}
4.3 spring事件
(1)spring提供了context start,stop,close,refresh等事件,ApplicationListener — onApplicationEvent负责处理spring中的事件。
(2)我们可以通过实现ApplicationListener接口自行处理事件,也可以通过PublishListener自定义事件监听器。
使用默认的事件广播器 AbstractApplicationContexton — publishEvent ----> SimpleApplicationEventMulticaster — multicastEvent
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(); // #1 如果配置了Executor,使用Executor多线程处理
if (executor != null) {
executor.execute(new Runnable() {
public void run() {
invokeListener(listener, event);
}
});
}
else {
invokeListener(listener, event); // #2 否则单线程处理
}
}
}
5.注册事件监听器
AbstractApplicationContext — registerListeners将初始化事件监听器ApplicationListener,并绑定到事件广播器上。
protected void registerListeners() {
for (ApplicationListener<?> listener : getApplicationListeners()) { // #1 getApplicationListeners()获取的是AbstractApplicationContext --- applicationListeners,用户可以通过AbstractApplicationContext --- addApplicationListener添加事件监听器
将AbstractApplicationContext#applicationListeners注册到applicationEventMulticaster
getApplicationEventMulticaster().addApplicationListener(listener);
}
String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false); // #2 将上下文中的ApplicationListener注册到applicationEventMulticaster
for (String listenerBeanName : listenerBeanNames) {
getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
}
Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents; // #3 发布在此之前已发生的事件
this.earlyApplicationEvents = null;
if (earlyEventsToProcess != null) {
for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
getApplicationEventMulticaster().multicastEvent(earlyEvent);
}
}
}
6.构造热加载单例bean
AbstractApplicationContext — finishbeanfactoryInitialization
protected void finishbeanfactoryInitialization(ConfigurableListablebeanfactory beanfactory) {
// Initialize conversion service for this context.
if (beanfactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
beanfactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
beanfactory.setConversionService(
beanfactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)); //#1 初始化ConversionService,后面注入属性要使用
}
if (!beanfactory.hasEmbeddedValueResolver()) {
beanfactory.addEmbeddedValueResolver(new StringValueResolver() { //#2 初始化StringValueResolver,用于解析bean属性引用的properties配置
@Override
public String resolveStringValue(String strVal) {
return getEnvironment().resolvePlaceholders(strVal);
}
});
}
String[] weaverAwareNames = beanfactory.getBeanNamesForType(LoadTimeweaverAware.class, false, false); //#3 初始化LoadTimeweaverAware
for (String weaverAwareName : weaverAwareNames) {
getBean(weaverAwareName);
}
beanfactory.setTempClassLoader(null);
beanfactory.freezeConfiguration();
// Instantiate all remaining (non-lazy-init) singletons.
beanfactory.preInstantiateSingletons(); //#4 构造热加载单例bean
}
AbstractApplicationContext — preInstantiateSingletons
public void preInstantiateSingletons() throws BeansException {
...
List<String> beanNames = new ArrayList<String>(this.beanDeFinitionNames);
for (String beanName : beanNames) {
RootBeanDeFinition bd = getMergedLocalBeanDeFinition(beanName);
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) { // #1 判断是否为非抽象类的热加载单例bean
if (isfactorybean(beanName)) {
final factorybean<?> factory = (factorybean<?>) getBean(FACTORY_BEAN_PREFIX + beanName);
boolean isEagerInit;
if (System.getSecurityManager() != null && factory instanceof Smartfactorybean) {
isEagerInit = AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
@Override
public Boolean run() {
return ((Smartfactorybean<?>) factory).isEagerInit();
}
}, getAccessControlContext());
}
else {
isEagerInit = (factory instanceof Smartfactorybean &&
((Smartfactorybean<?>) factory).isEagerInit());
}
if (isEagerInit) {
getBean(beanName);
}
}
else {
getBean(beanName); // #2 构造bean:如果非factorybean,构造bean。如果factorybean并且factorybean.isEagerInit为true,构造bean。
}
}
}
...
}
7. 完成刷新 finishRefresh
LifecycleProcessor也是spring提供的扩展点, 通过它可以在spring content start,stop,onRefresh等时刻自定义一些额外操作
protected void finishRefresh() {
// Initialize lifecycle processor for this context.
initLifecycleProcessor(); // #1 初始化LifecycleProcessor
// Propagate refresh to lifecycle processor first.
getLifecycleProcessor().onRefresh(); // #2 调用LifecycleProcessor#onRefresh()方法
// Publish the final event.
publishEvent(new ContextRefreshedEvent(this)); // #3 发布事件
// Participate in LiveBeansView MBean, if active.
LiveBeansView.registerapplicationContext(this);
}
随心所往,看见未来。Follow your heart,see night!
*欢迎点赞、关注、留言,收藏及转发,一起学习、交流!
原文地址:https://www.jb51.cc/wenti/3282545.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。