AbstractApplicationContext#refresh

spring 关键方法

org.springframework.context.support.AbstractApplicationContext#refresh

这个方法 是 线程安全的

synchronized (this.startupShutdownMonitor) { }

第一步,资源相关,初始化 属性资源 并验证

org.springframework.context.support.AbstractApplicationContext#prepareRefresh

initPropertySources(); 该方法提供给子类实现,实现该方法的子类有:

// org.springframework.web.context.support.AbstractRefreshableWebApplicationContext#initPropertySources
protected void initPropertySources() {
		ConfigurableEnvironment env = getEnvironment();
		if (env instanceof ConfigurableWebEnvironment) {
			((ConfigurableWebEnvironment) env).initPropertySources(this.servletContext, this.servletConfig);
		}
	}

public static void initServletPropertySources(MutablePropertySources sources,
			@Nullable ServletContext servletContext, @Nullable ServletConfig servletConfig) {

		Assert.notNull(sources, "'propertySources' must not be null");
		String name = StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME;
		if (servletContext != null && sources.get(name) instanceof StubPropertySource) {
			sources.replace(name, new ServletContextPropertySource(name, servletContext));
		}
		name = StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME;
		if (servletConfig != null && sources.get(name) instanceof StubPropertySource) {
			sources.replace(name, new ServletConfigPropertySource(name, servletConfig));
		}
	}

// org.springframework.web.context.support.GenericWebApplicationContext#initPropertySources
protected void initPropertySources() {
		ConfigurableEnvironment env = getEnvironment();
		if (env instanceof ConfigurableWebEnvironment) {
			((ConfigurableWebEnvironment) env).initPropertySources(this.servletContext, null);
		}
	}


public static void initServletPropertySources(MutablePropertySources sources,
			@Nullable ServletContext servletContext, @Nullable ServletConfig servletConfig) {

		Assert.notNull(sources, "'propertySources' must not be null");
		String name = StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME;
		if (servletContext != null && sources.get(name) instanceof StubPropertySource) {
			sources.replace(name, new ServletContextPropertySource(name, servletContext));
		}
		name = StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME;
		if (servletConfig != null && sources.get(name) instanceof StubPropertySource) {
			sources.replace(name, new ServletConfigPropertySource(name, servletConfig));
		}
	}
// org.springframework.web.context.support.StaticWebApplicationContext#initPropertySources
protected void initPropertySources() {
		WebApplicationContextUtils.initServletPropertySources(getEnvironment().getPropertySources(),
				this.servletContext, this.servletConfig);
	}

public static void initServletPropertySources(MutablePropertySources sources,
			@Nullable ServletContext servletContext, @Nullable ServletConfig servletConfig) {

		Assert.notNull(sources, "'propertySources' must not be null");
		String name = StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME;
		if (servletContext != null && sources.get(name) instanceof StubPropertySource) {
			sources.replace(name, new ServletContextPropertySource(name, servletContext));
		}
		name = StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME;
		if (servletConfig != null && sources.get(name) instanceof StubPropertySource) {
			sources.replace(name, new ServletConfigPropertySource(name, servletConfig));
		}
	}

getEnvironment().validateRequiredProperties(); 验证属性值

// 获取 applicationListeners

// Store pre-refresh ApplicationListeners...
		if (this.earlyApplicationListeners == null) {
			this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
		}
		else {
			// Reset local application listeners to pre-refresh state.
			this.applicationListeners.clear();
			this.applicationListeners.addAll(this.earlyApplicationListeners);
		}

第二步:

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

org.springframework.context.support.AbstractApplicationContext#refreshBeanFactory 是一个抽象方法,有两个实现:

第一个实现:

org.springframework.context.support.AbstractRefreshableApplicationContext#refreshBeanFactory

首先 DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(getInternalParentBeanFactory());

配置 是否可以 覆盖bean 和 循环依赖

protected void customizeBeanFactory(DefaultListableBeanFactory beanFactory) {
		if (this.allowBeanDefinitionOverriding != null) {
			beanFactory.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
		}
		if (this.allowCircularReferences != null) {
			beanFactory.setAllowCircularReferences(this.allowCircularReferences);
		}
	}

org.springframework.context.support.AbstractRefreshableApplicationContext#loadBeanDefinitions 调用 该方法加载bean信息,该方法由子类实现:

org.springframework.context.support.AbstractXmlApplicationContext#loadBeanDefinitions(org.springframework.beans.factory.support.DefaultListableBeanFactory)

org.springframework.web.context.support.AnnotationConfigWebApplicationContext#loadBeanDefinitions

org.springframework.web.context.support.GroovyWebApplicationContext#loadBeanDefinitions(org.springframework.beans.factory.support.DefaultListableBeanFactory)

org.springframework.web.context.support.XmlWebApplicationContext#loadBeanDefinitions(org.springframework.beans.factory.support.DefaultListableBeanFactory)

第二个实现:

org.springframework.context.support.GenericApplicationContext#refreshBeanFactory

protected final void refreshBeanFactory() throws IllegalStateException {
		if (!this.refreshed.compareAndSet(false, true)) {
			throw new IllegalStateException(
					"GenericApplicationContext does not support multiple refresh attempts: just call 'refresh' once");
		}
		this.beanFactory.setSerializationId(getId());
	}

因为 spring boot 启动 servlet模式使用的是 org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext 继承自 org.springframework.web.context.support.GenericWebApplicationContext,因此 这里实际基本等于啥都没做。而 beanfactory 在实例化 时构造。

public GenericApplicationContext() {
		this.beanFactory = new DefaultListableBeanFactory();
	}

第三步:

prepareBeanFactory(beanFactory);

设置 类加载器

beanFactory.setBeanClassLoader(getClassLoader());

设置Bean表达式解析器,以便解析Bean定义中的SpEL表达式

beanFactory.setBeanExpressionResolver(newStandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));

 注册资源编辑器注册器,用于自定义属性编辑器支持

beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

// 添加ApplicationContextAwareProcessor,使得Bean能感知到ApplicationContext,加入private final List<BeanPostProcessor> beanPostProcessors = new CopyOnWriteArrayList<>();

beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));

// 配置BeanFactory忽略特定接口的依赖注入,这些接口的实现通常由框架直接提供服务,加入private final Set<Class<?>> ignoredDependencyInterfaces = new HashSet<>();

beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);

// 注册可解析依赖:BeanFactory、ResourceLoader、ApplicationEventPublisher和ApplicationContext本身

beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
beanFactory.registerResolvableDependency(ResourceLoader.class, this);
beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
beanFactory.registerResolvableDependency(ApplicationContext.class, this);

    // 添加早期后处理器,用于检测内部Bean作为ApplicationListener

beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));

    // 如果存在LoadTimeWeaver,准备进行类加载期织入的配置

if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
// Set a temporary ClassLoader for type matching.

beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}

    // 注册默认的环境相关Bean,如Environment、系统属性和系统环境变量

f (!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());
}

第四步:

postProcessBeanFactory(beanFactory);

这个方法的实现比较多,有8个

// 	org.springframework.web.context.support.AbstractRefreshableWebApplicationContext#postProcessBeanFactory
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
		beanFactory.addBeanPostProcessor(new ServletContextAwareProcessor(this.servletContext, this.servletConfig));
		beanFactory.ignoreDependencyInterface(ServletContextAware.class);
		beanFactory.ignoreDependencyInterface(ServletConfigAware.class);

		WebApplicationContextUtils.registerWebApplicationScopes(beanFactory, this.servletContext);
		WebApplicationContextUtils.registerEnvironmentBeans(beanFactory, this.servletContext, this.servletConfig);
	}

// org.springframework.boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext#postProcessBeanFactory
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
		super.postProcessBeanFactory(beanFactory);
		if (!ObjectUtils.isEmpty(this.basePackages)) {
			this.scanner.scan(this.basePackages);
		}
		if (!this.annotatedClasses.isEmpty()) {
			this.reader.register(ClassUtils.toClassArray(this.annotatedClasses));
		}
	}

// org.springframework.boot.web.servlet.context.AnnotationConfigServletWebApplicationContext#postProcessBeanFactory
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
		super.postProcessBeanFactory(beanFactory);
		if (!ObjectUtils.isEmpty(this.basePackages)) {
			this.scanner.scan(this.basePackages);
		}
		if (!this.annotatedClasses.isEmpty()) {
			this.reader.register(ClassUtils.toClassArray(this.annotatedClasses));
		}
	}
// org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext#postProcessBeanFactory
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
		super.postProcessBeanFactory(beanFactory);
		if (this.basePackages != null && this.basePackages.length > 0) {
			this.scanner.scan(this.basePackages);
		}
		if (!this.annotatedClasses.isEmpty()) {
			this.reader.register(ClassUtils.toClassArray(this.annotatedClasses));
		}
	}

// org.springframework.web.context.support.GenericWebApplicationContext#postProcessBeanFactory
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
		if (this.servletContext != null) {
			beanFactory.addBeanPostProcessor(new ServletContextAwareProcessor(this.servletContext));
			beanFactory.ignoreDependencyInterface(ServletContextAware.class);
		}
		WebApplicationContextUtils.registerWebApplicationScopes(beanFactory, this.servletContext);
		WebApplicationContextUtils.registerEnvironmentBeans(beanFactory, this.servletContext);
	}
// org.springframework.jca.context.ResourceAdapterApplicationContext#postProcessBeanFactory
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        beanFactory.addBeanPostProcessor(new BootstrapContextAwareProcessor(this.bootstrapContext));
        beanFactory.ignoreDependencyInterface(BootstrapContextAware.class);
        beanFactory.registerResolvableDependency(BootstrapContext.class, this.bootstrapContext);
        BootstrapContext var10002 = this.bootstrapContext;
        beanFactory.registerResolvableDependency(WorkManager.class, var10002::getWorkManager);
    }
}
//org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext#postProcessBeanFactory
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
		beanFactory.addBeanPostProcessor(new WebApplicationContextServletContextAwareProcessor(this));
		beanFactory.ignoreDependencyInterface(ServletContextAware.class);
		registerWebApplicationScopes();
	}
//org.springframework.web.context.support.StaticWebApplicationContext#postProcessBeanFactory
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
		beanFactory.addBeanPostProcessor(new ServletContextAwareProcessor(this.servletContext, this.servletConfig));
		beanFactory.ignoreDependencyInterface(ServletContextAware.class);
		beanFactory.ignoreDependencyInterface(ServletConfigAware.class);

		WebApplicationContextUtils.registerWebApplicationScopes(beanFactory, this.servletContext);
		WebApplicationContextUtils.registerEnvironmentBeans(beanFactory, this.servletContext, this.servletConfig);
	}

第五步:

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

public List<BeanFactoryPostProcessor> getBeanFactoryPostProcessors() {
		return this.beanFactoryPostProcessors;
	}

. PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());

这里也比较复杂,该函数用于在Spring应用程序上下文中调用BeanFactoryPostProcessor和BeanDefinitionRegistryPostProcessor的实例。这些处理器可以在Spring容器实例化任何bean之前修改bean的定义或bean工厂的配置。

第一部分:调用 BeanDefinitionRegistryPostProcessor

行 org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor#postProcessBeanDefinitionRegistry

从bean工厂中读取所有的 BeanDefinitionRegistryPostProcessor

优先排序 并调用 实现了 org.springframework.core.PriorityOrdered 接口的。

然后排序 并调用 实现了 org.springframework.core.Ordered 接口的

最后调用剩下的

调用 所有的 org.springframework.beans.factory.config.BeanFactoryPostProcessor#postProcessBeanFactory

第二部分:调用 BeanFactoryPostProcessor

也是按照PriorityOrdered/Ordered 顺序调用

第六步:registerBeanPostProcessors(beanFactory);

这一步看着停复杂,实际就做一件事,读取所有的 BeanPostProcessor,按照优先级排序后

写入 org.springframework.beans.factory.support.AbstractBeanFactory#beanPostProcessors

第七/八步:

initMessageSource();

initApplicationEventMulticaster();

第九步:

onRefresh();

实现类也挺多

org.springframework.web.context.support.AbstractRefreshableWebApplicationContext#onRefresh

protected void onRefresh() {
this.themeSource = UiApplicationContextUtils.initThemeSource(this);
}

org.springframework.web.context.support.GenericWebApplicationContext#onRefresh

protected void onRefresh() {
this.themeSource = UiApplicationContextUtils.initThemeSource(this);
}

org.springframework.boot.web.reactive.context.ReactiveWebServerApplicationContext#onRefresh

protected void onRefresh() {
super.onRefresh();
try {
createWebServer();
}
catch (Throwable ex) {
throw new ApplicationContextException("Unable to start reactive web server", ex);
}
}

org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext#onRefresh

protected void onRefresh() {
super.onRefresh();
try {
createWebServer();
}
catch (Throwable ex) {
throw new ApplicationContextException("Unable to start web server", ex);
}
}

org.springframework.web.context.support.StaticWebApplicationContext#onRefresh

protected void onRefresh() {
this.themeSource = UiApplicationContextUtils.initThemeSource(this);
}

第十步:

registerListeners();

注册 ApplicationListener

第十一步:

finishBeanFactoryInitialization(beanFactory);

完成bean的实例化

第十二步:

/**
 * 完成此上下文的刷新操作,包括调用生命周期处理器的onRefresh()方法,
 * 发布ContextRefreshedEvent事件,以及参与LiveBeansView MBean(如激活)。
 */
protected void finishRefresh() {
    // 清除上下文级别的资源缓存(例如扫描期间获取的ASM元数据)。
    clearResourceCaches();

    // 初始化此上下文的生命周期处理器。
    initLifecycleProcessor();

    // 首先将刷新操作传播给生命周期处理器。
    getLifecycleProcessor().onRefresh();

    // 发布最终的刷新事件。
    publishEvent(new ContextRefreshedEvent(this));

    // 如LiveBeansView MBean处于活动状态,注册此应用上下文以参与其中。
    LiveBeansView.registerApplicationContext(this);
}

 

finally:

protected void resetCommonCaches() {
ReflectionUtils.clearCache();
AnnotationUtils.clearCache();
ResolvableType.clearCache();
CachedIntrospectionResults.clearClassLoader(getClassLoader());
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值