SpringBoot启动流程分析六 refreshContext()

前面讲完了prepareContext流程,接下来讲refreshContext方法:先进入refreshContext方法:最终执行方法是AbstractApplicationContext类public void refresh() throws BeansException, IllegalStateException { synchronized(this.startupShutdownMonitor) { // 准备刷新 this.pr
摘要由CSDN通过智能技术生成

前面讲完了prepareContext流程,接下来讲refreshContext方法:

先进入refreshContext方法:最终执行方法是AbstractApplicationContext类

public void refresh() throws BeansException, IllegalStateException {
   
        synchronized(this.startupShutdownMonitor) {
   
        	// 准备刷新
            this.prepareRefresh();
            // 为上下文中准备bean工厂
            ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();
            this.prepareBeanFactory(beanFactory);

            try {
   
            	// 允许上下文子类中对bean工厂进行后处理
                this.postProcessBeanFactory(beanFactory);
                // 在bean创建之前调用BeanFactoryPostProcessors后置处理方法
                this.invokeBeanFactoryPostProcessors(beanFactory);
                // 注册BeanPostProcessor
                this.registerBeanPostProcessors(beanFactory);
                // 注册DelegatingMessageSource
                this.initMessageSource();
                // 注册multicaster
                this.initApplicationEventMulticaster();
                // 创建内置的Servlet容器
                this.onRefresh();
                // 注册Listener
                this.registerListeners();
                // 完成BeanFactory初始化,初始化剩余单例bean
                this.finishBeanFactoryInitialization(beanFactory);
                // 发布对应事件
                this.finishRefresh();
            } catch (BeansException var9) {
   
                if (this.logger.isWarnEnabled()) {
   
                    this.logger.warn("Exception encountered during context initialization - cancelling refresh attempt: " + var9);
                }

                this.destroyBeans();
                this.cancelRefresh(var9);
                throw var9;
            } finally {
   
                this.resetCommonCaches();
            }

        }
    }

1、准备刷新this.prepareRefresh():

{
   
		//系统启动时间
        this.startupDate = System.currentTimeMillis();
         //是否关闭标识,false
        this.closed.set(false);
        //是否活跃标识,true
        this.active.set(true);
        if (this.logger.isDebugEnabled()) {
   
            if (this.logger.isTraceEnabled()) {
   
                this.logger.trace("Refreshing " + this);
            } else {
   
                this.logger.debug("Refreshing " + this.getDisplayName());
            }
        }

	// 调用子类重写后的方法替换servlet相关属性源,即子类自定义个性化的属性设置方法
        this.initPropertySources();
        // 这里是验证由ConfigurablePropertyResolver#setRequiredProperties()方法指定的属性,解析为非空值,如果没有设置的话这个方法就不会执行什么操作。

        this.getEnvironment().validateRequiredProperties();
        if (this.earlyApplicationListeners == null) {
   
        // Store pre-refresh ApplicationListeners
            this.earlyApplicationListeners = new LinkedHashSet(this.applicationListeners);
        } else {
   
            this.applicationListeners.clear();
            this.applicationListeners.addAll(this.earlyApplicationListeners);
        }

        this.earlyApplicationEvents = new LinkedHashSet();
    }

StaticWebApplicationContext,GenericWebApplicationContext,AbstractRefreshableWebApplicationContext都会实现 this.initPropertySources()方法:

//AbstractRefreshableWebApplicationContext
protected void initPropertySources() {
   
        ConfigurableEnvironment env = this.getEnvironment();
        if (env instanceof ConfigurableWebEnvironment) {
   
            ((ConfigurableWebEnvironment)env).initPropertySources(this.servletContext, this.servletConfig);
        }

    }
//GenericWebApplicationContext
protected void initPropertySources() {
   
        ConfigurableEnvironment env = this.getEnvironment();
        if (env instanceof ConfigurableWebEnvironment) {
   
            ((ConfigurableWebEnvironment)env).initPropertySources(this.servletContext, (ServletConfig)null);
        }

    }
//StaticWebApplicationContext
 protected void initPropertySources() {
   
        WebApplicationContextUtils.initServletPropertySources(this.getEnvironment().getPropertySources(), this.servletContext, this.servletConfig);
    }

2、获取BeanFactory
ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();
该方法主要获取需要统一各context的beanFactory 属性

protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
   
        this.refreshBeanFactory();
        return this.getBeanFactory();
    }

先看refreshBeanFactory方法,由子类执行,保证有一些子类context的此属性没有赋值
在这里插入图片描述
AbstractRefreshableApplicationContext类中:

protected final void refreshBeanFactory() throws BeansException {
   
//如果有该context类中已经设置过了BeanFactory则销毁,保证单例
        if (this.hasBeanFactory()) {
   
            this.destroyBeans();
            this.closeBeanFactory();
        }

        try {
   
            DefaultListableBeanFactory beanFactory = this.createBeanFactory();
            //设置唯一id
            beanFactory.setSerializationId(this.getId());
            this.customizeBeanFactory(beanFactory);
            this.loadBeanDefinitions(beanFactory);
            synchronized(this.beanFactoryMonitor) {
   
                this.beanFactory = beanFactory;
            }
        } catch (IOException var5) {
   
            throw new ApplicationContextException("I/O error parsing bean definition source for " + this.getDisplayName(), var5);
        }
    }

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");
        } else {
   
            this.beanFactory.setSerializationId(this.getId());
        }
    }

getBeanFactory:

public abstract ConfigurableListableBeanFactory getBeanFactory() throws IllegalStateException;

最后返回的是ConfigurableListableBeanFactory 实例

3、设置BeanFactory, this.prepareBeanFactory(beanFactory)

	protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
   
		// 设置beanFactory的类加载器、支持表达式解析器
		beanFactory.setBeanClassLoader(getClassLoader());
		beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
		beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment())
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值