Spring源码分析:refresh()

refresh()中共有13个方法,分别为

1.prepareRefresh()

容器刷新前的准备,设置上下文状态,获取属性,验证必要的属性等

   protected void prepareRefresh() {
		//spring启动时间
		this.startupDate = System.currentTimeMillis();
		//spring标记为未关闭
		this.closed.set(false);
		//spring激活状态
		this.active.set(true);
		//记录日志
		if (logger.isDebugEnabled()) {
			if (logger.isTraceEnabled()) {
				logger.trace("Refreshing " + this);
			}
			else {
				logger.debug("Refreshing " + getDisplayName());
			}
		}
		//点进去会发现没有任何内容,是个方法扩展点。留给子类覆盖,初始化属性资源
		initPropertySources();
		// 创建并获取环境对象,验证需要的属性文件是否都已经放入环境中
		getEnvironment().validateRequiredProperties();
		// 判断刷新前的应用程序监听器集合是否为空,如果为空,则将监听器添加到此集合中
		if (this.earlyApplicationListeners == null) {
			this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
		}
		else {
		//如果不等于空,则清空集合元素对象
			this.applicationListeners.clear();
	this.applicationListeners.addAll(this.earlyApplicationListeners);
		}
		// 创建刷新前的监听事件集合
		this.earlyApplicationEvents = new LinkedHashSet<>();
	}

2.obtainFreshBeanFactory()

obtainFreshBeanFactory方法主要作用:创建BeanFactory对象,并解析xml封装成BeanDefinition对象。(获取新的beanFactory,销毁原有beanFactory、为xml中定义的每个bean生成BeanDefinition等,注意此处是获取新的,销毁旧的,这就是刷新的意义)

补充:如果Spring注册bean采用注解的形式,此方法中AnnotatedBeanDefinitionReader仅仅只是将我们的启动类转化为BeanDefinition注册到spring容器的BeanDefinitionMap中,后续在执行BeanFactoryPostProcessor时,会以此为起点,开始扫描项目中的Controller、Service等等注册到容器中。

public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext {
...
  			//			* 1、创建BeanFactory对象
			//			* 2、xml解析
			//			* 	传统标签解析:bean、import等
			//			* 	自定义标签解析 如:
			//			* 	自定义标签解析流程:
			//			* 		a、根据当前解析标签的头信息找到对应的namespaceUri
			//			* 		b、加载spring所以jar中的spring.handlers文件。并建立映射关系
			//			* 		c、根据namespaceUri从映射关系中找到对应的实现了NamespaceHandler接口的类
			//			* 		d、调用类的init方法,init方法是注册了各种自定义标签的解析类
			//			* 		e、根据namespaceUri找到对应的解析类,然后调用paser方法完成标签解析
			//			*
			//			* 3、把解析出来的xml标签封装成BeanDefinition对象
		protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
			   // 1.刷新 BeanFactory,由AbstractRefreshableApplicationContext实现,初始化beanFactory,并执行加载和解析配置操作
				refreshBeanFactory();
				//返回beanFactory实例
				return getBeanFactory();
		}
...
}


为什么先创建BeanFactory对象,再加载解析xml文件,顺序不能反过来吗?
因为加载解析xml文件,生成的BeanDefinition对象,需要存放在BeanFactory的BeanDefinitionMap中,故需要先创建BeanFactory。

3.prepareBeanFactory(beanFactory)

beanFactory的准备工作,对各种属性进行填充,对 beanFactory 进行功能扩展,如增加 SPEL 支持和属性编辑器等

protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
        //设置类加载器:存在则直接设置/不存在则新建一个默认类加载器
        beanFactory.setBeanClassLoader(getClassLoader());
 
       //设置EL表达式解析器(Bean初始化完成后填充属性时会用到)
        beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
 
       //设置属性注册解析器PropertyEditor
        beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
 
     // 将当前的ApplicationContext对象交给ApplicationContextAwareProcessor类来处理,从而在Aware接口实现类中的注入applicationContext
        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);
 
        //注册可以解析的自动装配
        // MessageSource registered (and found for autowiring) as a bean.
        beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
        beanFactory.registerResolvableDependency(ResourceLoader.class, this);
        beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
        beanFactory.registerResolvableDependency(ApplicationContext.class, this);
 
        //如果当前BeanFactory包含loadTimeWeaver Bean,说明存在类加载期织入AspectJ,则把当前BeanFactory交给类加载期BeanPostProcessor实现类LoadTimeWeaverAwareProcessor来处理,从而实现类加载期织入AspectJ的目的。
        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()));
        }
 
        //注册当前容器环境environment组件Bean
        if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
            beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
        }
 
       //注册系统配置systemProperties组件Bean
        if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
            beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
        }
 
       //注册系统环境systemEnvironment组件Bean
        if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
            beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
        }
    }

4.postProcessBeanFactory(beanFactory)

空方法,留给子类扩展

5.invokeBeanFactoryPostProcessors(beanFactory)

作用:调用Bean工厂的后置处理器

/*
 * BeanDefinitionRegistryPostProcessor
* BeanFactoryPostProcessor
* Bean工厂的后置处理器 、完成对这两个接口的调用
* * */
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
        //传入Bean工厂并获取容器中的Bean工厂后置处理器(注意这里Bean工厂后置处理器还没有初始化)
        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()));
        }
    }


6.registerBeanPostProcessors(beanFactory)

作用:把实现了 BeanPostProcessor接口的类实例化并注册到工厂.

BeanPostProcessor接口是Spring中一个非常重要的接口,它的接口定义如下:

public interface BeanPostProcessor {

    Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;
    
    Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;
}
当你实现了这个接口的时候,Spring会保证在每一个bean对象初始化方法调用之前调用postProcessBeforeInitialization方法,在初始化方法调用之后调用postProcessAfterInitialization


public static void registerBeanPostProcessors(
        ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {

    //获取BeanFactory中注册的类型为BeanPostProcessor.class的bean名称。一般获取到的是实现了BeanPostProcessor接口的Bean
    String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);

    // BeanPostProcessor的目标计数
    int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
    // 添加BeanPostProcessorChecker(主要用于记录信息)到beanFactory中
    beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
    // 将BeanPostProcessors分为实现了PriorityOrdered接口,Ordered接口、普通的类型
    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)) {
            // 如果ppName对应的Bean实例实现了PriorityOrdered接口, 则拿到ppName对应的Bean实例并添加到priorityOrderedPostProcessors
            BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
            priorityOrderedPostProcessors.add(pp);
            if (pp instanceof MergedBeanDefinitionPostProcessor) {
                //如果ppName对应的Bean实例也实现了MergedBeanDefinitionPostProcessor接口,
                // 则将ppName对应的Bean实例添加到internalPostProcessors
                internalPostProcessors.add(pp);
            }
        }
        else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
            //如果ppName对应的Bean实例没有实现PriorityOrdered接口, 但是实现了Ordered接口, 则将ppName添加到orderedPostProcessorNames
            orderedPostProcessorNames.add(ppName);
        }
        else {
            nonOrderedPostProcessorNames.add(ppName);
        }
    }
    // 对priorityOrderedPostProcessors进行排序
    sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
    // priorityOrderedPostProcessors
    registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
    // 注册实现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(orderedPostProcessors, beanFactory);
    // 注册
    registerBeanPostProcessors(beanFactory, orderedPostProcessors);
    // 注册所有常规的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);
    // 最后, 重新注册所有内部BeanPostProcessors(相当于内部的BeanPostProcessor会被移到处理器链的末尾)
    // 排序
    sortPostProcessors(internalPostProcessors, beanFactory);
    // 注册
    registerBeanPostProcessors(beanFactory, internalPostProcessors);
    // 加入ApplicationListenerDetector
    beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}

7.initMessageSource()

主要作用:是初始化国际化文件。

8.initApplicationEventMulticaster()

初始化应用的事件广播器

protected void initApplicationEventMulticaster() {
    ConfigurableListableBeanFactory beanFactory = getBeanFactory();
    // 判断BeanFactory是否已经存在事件广播器(固定使用beanName=applicationEventMulticaster)
    if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
        // 如果已经存在,则将该bean赋值给applicationEventMulticaster
        this.applicationEventMulticaster =
                beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
        if (logger.isDebugEnabled()) {
            logger.debug("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
        }
    } else {
        // 如果不存在,则使用SimpleApplicationEventMulticaster
        this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
        // 并将SimpleApplicationEventMulticaster作为默认的事件广播器,注册到BeanFactory中
        beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
        if (logger.isDebugEnabled()) {
            logger.debug("Unable to locate ApplicationEventMulticaster with name '" +
                    APPLICATION_EVENT_MULTICASTER_BEAN_NAME +
                    "': using default [" + this.applicationEventMulticaster + "]");
        }
    }
}

9.onRefresh()

空方法,用于子类扩展

10.registerListeners()

注册监听器(在所有注册的bean中查找bean listener,注册到消息广播器中)

protected void registerListeners() {
    // Register statically specified listeners first.
    // 1.通过硬编码调用addApplicationListener方法添加的监听器处理(可以通过自定义ApplicationContextInitializer添加)
    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!
    // 2.通过配置文件或注解注入BeanFactory的监听器处理
    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...
    // 3.使用事件广播器,发布早期应用程序事件到相应的监听器
    Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
    this.earlyApplicationEvents = null;
    if (earlyEventsToProcess != null) {
        for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
            getApplicationEventMulticaster().multicastEvent(earlyEvent);
        }
    }
}

AppicationContext的事件机制是观察者模式的实现,按以下方式可以实现。
首先我们需要自定义一个事件类,此事件类是需要继承ApplicationEvent类
然后我们定义一个监听类,监听类作为一个Spring容器中的bean,同时需要实现ApplicationListner接口
然后我们就可以使用ApplicationContext的实例发布事件,相应监听类的实例(bean)负责监听具体的事件

11.finishBeanFactoryInitialization(beanFactory)

简单来说,就是实例化剩下的非懒加载的单实例对象
(即实例化bean,以及在bean的实例化通过各种各样的后置处理器完成bean的增强。)

如果想实例化,前提是不能是抽象类,不能是接口,非懒加载, 而且针对FactoryBean还有不同的处理模式

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

    // 检查上下文中是否存在类型转换器
	if (!beanFactory.hasEmbeddedValueResolver()) {
		beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
	}
    // 尽早初始化LoadTimeWeaverAware bean,以便尽早注册它们的转换器。
	// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
	String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
	for (String weaverAwareName : weaverAwareNames) {
		getBean(weaverAwareName);
	}

	// Stop using the temporary ClassLoader for type matching.
    // 禁止使用临时类加载器进行类型匹配
	beanFactory.setTempClassLoader(null);

	// Allow for caching all bean definition metadata, not expecting further changes
    // 允许缓存所有的bean的定义数据
	beanFactory.freezeConfiguration();

	// Instantiate all remaining (non-lazy-init) singletons.
    // 准备实例化bean
	beanFactory.preInstantiateSingletons();
}

在这里插入图片描述

该方法中使用反射创建了bean实例;然后调用populateBean()方法填充属性,将各个属性值注入,其中可能存在依赖于其他bean的属性,则会递归初始化依赖的bean;执行aware接口所对应的方法;然后执行BeanPostProcessor:before,init-method方法,BeanPostProcessor:after方法。

12.finishRefresh()

完成刷新过程,通知声明周期处理器LifecycleProcessor刷新过程,同时发出ContextRefreshEvent通知别人

将这12个方法,按作用简单划分一下:

1 为准备环境
2 3 4 5 6 为准备 BeanFactory
7 8 9 10 12 为准备 ApplicationContext
11 为初始化 BeanFactory 中非延迟单例 bean

Spring源码分析:refresh()_第1张图片

https://blog.csdn.net/weixin_47061482/article/details/115406213
https://segmentfault.com/a/1190000020494692

你可能感兴趣的:(Spring源码,spring,java,后端)