Spring源码分析:IOC容器的刷新 - refresh()

发布时间:2024年01月05日
  1. 面试常见问题:
    1. bean生命周期
    2. 循环依赖
    3. 三级缓存
    4. FactoryBean 和 beanFactory
    5. ApplicationContext 和 BeanFactory 的区别
    6. 设计模式
  2. bean定义信息BeanDefinition读取xml配置文件,通过抽象接口BeanDefinitionReader读取配置文件规范,源码当中的ConfigurableListableBeanFactory部分内容就是读取.xml配置文件

?

实例化:在堆中开辟一块空间,属性都是默认值。

初始化:给属性完成赋值操作,调用具体的初始化方法

?

?

BeanFactory对应源码当中的prepareRefresh( )和prepareBeanFactory( ),BeanFactoryPostProcessor是对beanDefinition的扩展 ,可以set很多扩展信息,BeanFactoryPostProcessor对应源码当中的invokeBeanFactoryPostProcessors( )和registerBeanPostProcessors( )

?

?

Environment:环境,包含 envproperties, 为了方便使用,在容器创建的时候会提前将系统的相关属性加载到StandardEnvironment对象当中,方便后续的使用

源码AbstractApplicationContext当中的refresh( )方法,通过调用refresh( )方法了解IOC容器创建原理(执行顺序从上到下)

prepareRefresh( ):程序启动标志位,准备刷新上下文方法,用于设置准备刷新前的一些参数
ConfigurableListableBeanFactory beanFactory =obtainFreshBeanFactory():获取BeanFactory,读取.xml配置文件,通过配置文件读取Bean,内部调用refreshBeanFactory( )和getBeanFactory( )
prepareBeanFactory(beanFactory):初始化Bean工厂,设置各种基础属性,比如classLoader,以及addBeanPostProcessor方法
postProcessBeanFactory(beanFactory):BeanFactoryPostProcessor,BeanFactory配置好的后置扩展操作
invokeBeanFactoryPostProcessors(beanFactory):执行BeanFactory的后置处理
registerBeanPostProcessors(beanFactory):注册BeanPostProcessors到BeanFacotry中并排序
initMessageSource( ) 国际化处理
initApplicationEventMulticaster( ) 初始化上下文事件的广播/多播器,方便后续发布监听事件
onRefresh( ):子类实现,在此创建web容器,并提前生成容器所需的bean及其对应的生命周期
registerListeners():给广播器中注册监听器
finishBeanFactoryInitialization(beanFactory):初始化所有非懒加载单例Bean
finishRefresh( ):完成刷新,发布上下文刷新完毕事件
	protected void prepareRefresh() {
		// 设置基础属性,设置当前状态为活跃/启动
		this.startupDate = System.currentTimeMillis();
		this.closed.set(false);
		this.active.set(true);
        // log打印

		// 交由子类实现,用于加载初始化资源属性.
		initPropertySources();

		// 校验所需要的环境变量是否已经加载进来
		getEnvironment().validateRequiredProperties();

		// 保留未生成Context时加载的Linsteners监听器
		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);
		}

		// 创建ApplicationEvent监听事件容器
		this.earlyApplicationEvents = new LinkedHashSet<>();
	}
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
	refreshBeanFactory();
	return getBeanFactory();
}

protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
	// 设置BeanFactory的ClassLoader
	beanFactory.setBeanClassLoader(getClassLoader());
	// 判断是否需要加载Spring-Spel表达式解析器.默认加载
	if (!shouldIgnoreSpel) {
		beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
	}
	// 添加属性编辑器用于自定义属性设置覆盖
	beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

	// 添加默认注册Bean前加入BeanPostProcessor用于Bean初始化前进行操作: 如果Bean实现了某个Aware则调用对应方法.可查看ApplicationContextAwareProcessor.ApplicationContextAwareProcessor方法,自定义Bean可进行拓展
	beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
	// 忽略一些系统级接口依赖,这些方法在上面的Processor中检查回调中会执行.
	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.ignoreDependencyInterface(ApplicationStartup.class);

	// 设置注册不能自动创建的Bean依赖
	beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
	beanFactory.registerResolvableDependency(ResourceLoader.class, this);
	beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
	beanFactory.registerResolvableDependency(ApplicationContext.class, this);

	// 添加Bean初始化后操作,如果有该单例监听器Bean就加入到上下文监听器容器中
	beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));

	// 加入AspectJ支持(静态代理,启动时会改变被代理类字节码进行增强https://blog.csdn.net/crazyzhb2012/article/details/53827540 | https://developer.aliyun.com/article/574571)
	if (!NativeDetector.inNativeImage() && 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
	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());
	}
	if (!beanFactory.containsLocalBean(APPLICATION_STARTUP_BEAN_NAME)) {
		beanFactory.registerSingleton(APPLICATION_STARTUP_BEAN_NAME, getApplicationStartup());
	}
}
// ServletWebServerApplicationContext中的方法
// 作为BeanFactory设置好之后Bean加载初始化前拓展扫描的后置操作
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
	beanFactory.addBeanPostProcessor(new WebApplicationContextServletContextAwareProcessor(this));
	beanFactory.ignoreDependencyInterface(ServletContextAware.class);
	// 最主要是最后这步,为BeanFactory注册了request、session的web域
	// 并注册了ServletRequest、ServletResponse、HttpSession、WebRequest到容器中
	registerWebApplicationScopes();
}
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
    // 调用执行默认的和自定义的BeanDefinitionRegistryPostProcessor和BeanFactoryPostProcessor类方法
	PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
	//···其他
}
//注册BeanPostProcessors到BeanFacotry中并排序,并未执行.涉及到.涉及到Bean生命周期执行
protected void initMessageSource() {
	ConfigurableListableBeanFactory beanFactory = getBeanFactory();
	if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
		this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
		// Make MessageSource aware of parent MessageSource.
		if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
			HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
			if (hms.getParentMessageSource() == null) {
				// Only set parent context as parent MessageSource if no parent MessageSource
				// registered already.
				hms.setParentMessageSource(getInternalParentMessageSource());
			}
		}
		if (logger.isTraceEnabled()) {
			logger.trace("Using MessageSource [" + this.messageSource + "]");
		}
	}
	else {
		// Use empty MessageSource to be able to accept getMessage calls.
		DelegatingMessageSource dms = new DelegatingMessageSource();
		dms.setParentMessageSource(getInternalParentMessageSource());
		this.messageSource = dms;
		beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
		if (logger.isTraceEnabled()) {
			logger.trace("No '" + MESSAGE_SOURCE_BEAN_NAME + "' bean, using [" + this.messageSource + "]");
		}
	}
}
//事件广播器用于Spring事件通知机制,监听器通过指定监听事件,当广播器广播该事件时会执行对应监听器方法.
//该方法表示如果有自定义广播器则使用自定义广播器没有则创建一个SimpleApplicationEventMulticaster.可自定义拓展让广播器监听事件异步执行
//保存事件和对应监听器列表映射,发布事件后会找到该事件的所有监听器.如果由线程池则异步执行.没有则同步执行
protected void initApplicationEventMulticaster() {
    ConfigurableListableBeanFactory beanFactory = getBeanFactory();
    // 如果用户手动新建了一个名为applicationEventMulticaster类型为ApplicationEventMulticaster的bean,则将这个bean作为事件广播器
    if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
        this.applicationEventMulticaster =
                beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
    }
    else {
        // 否则新建一个SimpleApplicationEventMulticaster作为默认的事件广播器
        this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
        beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
    }
}
//给广播器中注册监听器,发布广播器未初始化时加载的事件
protected void registerListeners() {
	// 将Application启动时加载的Linsteners加入广播器中
	for (ApplicationListener<?> listener : getApplicationListeners()) {
		getApplicationEventMulticaster().addApplicationListener(listener);
	}

	// 先将常规的监听器Bean名称放入,后续再创建
	String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
	for (String listenerBeanName : listenerBeanNames) {
		getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
	}

	// 早期Application事件发布
	Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
	this.earlyApplicationEvents = null;
	if (!CollectionUtils.isEmpty(earlyEventsToProcess)) {
		for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
			getApplicationEventMulticaster().multicastEvent(earlyEvent);
		}
	}
}

参考文章:AbstractApplicationContext.refresh()应用上下文刷新方法分析_abstractapplicationcontext refresh方法 调用时机-CSDN博客

文章来源:https://blog.csdn.net/adobe754/article/details/135391926
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。