8.1。 SpringBoot启动流程--把spring应用跑起来

创建IOC容器 createApplicationContext()

protected ConfigurableApplicationContext createApplicationContext() {
        return this.applicationContextFactory.create(this.webApplicationType);
    }
=============根据当前的应用类型(Servlet)创建容器
//当前会创建AnnotationConfigServletWebServerApplicationContext
ApplicationContextFactory DEFAULT = (webApplicationType) -> {
        try {
            switch (webApplicationType) {
            case SERVLET:
                return new AnnotationConfigServletWebServerApplicationContext();
            case REACTIVE:
                return new AnnotationConfigReactiveWebServerApplicationContext();
            default:
                return new AnnotationConfigApplicationContext();
            }
        }
        catch (Exception ex) {
            throw new IllegalStateException("Unable create a default ApplicationContext instance, "
                    + "you may need a custom ApplicationContextFactory", ex);
        }
    };

准备ApplicationContext IOC容器的基本信息 prepareContext()

private void prepareContext(DefaultBootstrapContext bootstrapContext, ConfigurableApplicationContext context,
            ConfigurableEnvironment environment, SpringApplicationRunListeners listeners,
            ApplicationArguments applicationArguments, Banner printedBanner) {
        //保存前面的基础环境
        context.setEnvironment(environment);
        //IOC容器的后置处理流程。
        postProcessApplicationContext(context);
        //应用初始化器:applyInitializers
        applyInitializers(context);
        //遍历所有的 listener 调用 contextPrepared
        //ioc容器的环境准备就绪了(contextPrepared方法的源码在下面)
        listeners.contextPrepared(context);
        //引导上下文的环境关闭了
        bootstrapContext.close(context);
        if (this.logStartupInfo) {
            logStartupInfo(context.getParent() == null);
            logStartupProfileInfo(context);
        }
        // Add boot specific singleton beans
        //拿到bean工厂
        ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
        //注册单实例
        beanFactory.registerSingleton("springApplicationArguments", applicationArguments);
        //打印banner
        if (printedBanner != null) {
            beanFactory.registerSingleton("springBootBanner", printedBanner);
        }
        if (beanFactory instanceof DefaultListableBeanFactory) {
            ((DefaultListableBeanFactory) beanFactory)
                    .setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
        }
        if (this.lazyInitialization) {
            context.addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor());
        }
        // Load the sources
        Set sources = getAllSources();
        Assert.notEmpty(sources, "Sources must not be empty");
        load(context, sources.toArray(new Object[0]));
        //listeners:监听器
        listeners.contextLoaded(context);
    }

================== postProcessApplicationContext(context);
protected void postProcessApplicationContext(ConfigurableApplicationContext context) {
        if (this.beanNameGenerator != null) {
//注册组件
            context.getBeanFactory().registerSingleton(AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR,
                    this.beanNameGenerator);
        }

        if (this.resourceLoader != null) {
        //读取配置文件的资源
            if (context instanceof GenericApplicationContext) {
                ((GenericApplicationContext) context).setResourceLoader(this.resourceLoader);
            }

            if (context instanceof DefaultResourceLoader) {
        //资源加载器
                ((DefaultResourceLoader) context).setClassLoader(this.resourceLoader.getClassLoader());
            }
        }

        //准备类型转换器
        if (this.addConversionService) {
            context.getBeanFactory().setConversionService(ApplicationConversionService.getSharedInstance());
        }
    }

===================applyInitializers(context)
protected void applyInitializers(ConfigurableApplicationContext context) {
//遍历所有的 ApplicationContextInitializer。调用 initialize。来对ioc容器进行初始化扩展功能
        for (ApplicationContextInitializer initializer : getInitializers()) { //之前从spring.factories找出来的七个Initializer
            Class requiredType = GenericTypeResolver.resolveTypeArgument(initializer.getClass(),
                    ApplicationContextInitializer.class);
            Assert.isInstanceOf(requiredType, context, "Unable to call initializer.");
            initializer.initialize(context);
        }
    }

@Override
    public void initialize(ConfigurableApplicationContext context) {
        ConfigurableEnvironment environment = context.getEnvironment();
        List> initializerClasses = getInitializerClasses(environment);
    //如果initializerClasses不为空,就把他们实例化。
        if (!initializerClasses.isEmpty()) {
            applyInitializerClasses(context, initializerClasses);
        }
    }

===========contextPrepared()
void contextPrepared(ConfigurableApplicationContext context) {
        doWithListeners("spring.boot.application.context-prepared", (listener) -> listener.contextPrepared(context));
}

private void doWithListeners(String stepName, Consumer listenerAction) {
        doWithListeners(stepName, listenerAction, null);
}

private void doWithListeners(String stepName, Consumer listenerAction,
            Consumer stepAction) {
        StartupStep step = this.applicationStartup.start(stepName);
        //拿到所有的listeners
        //实际上是EventPublishRunListenr:通知所有的监听器contextPrepared容器的上下文环境已经准备好了
        this.listeners.forEach(listenerAction);
        if (stepAction != null) {
            stepAction.accept(step);
        }
        step.end();
}

================contextLoaded()
void contextLoaded(ConfigurableApplicationContext context) {
        doWithListeners("spring.boot.application.context-loaded", (listener) -> listener.contextLoaded(context));
}

private void doWithListeners(String stepName, Consumer listenerAction) {
        doWithListeners(stepName, listenerAction, null);
}

private void doWithListeners(String stepName, Consumer listenerAction,
            Consumer stepAction) {
        StartupStep step = this.applicationStartup.start(stepName);
    //所有的监听器去调用contextLoaded(context)
    //通知所有的监听器contextLoaded;容器的上下文环境已经加载好了
        this.listeners.forEach(listenerAction);
        if (stepAction != null) {
            stepAction.accept(step);
        }
        step.end();
}

(listener) -> listener.contextLoaded(context) 

                            
                        
                    
                    
                    

你可能感兴趣的:(springbootjava)