springboot sourcecode: SpringApplication.prepareContext

this.prepareContext(bootstrapContext//引导程序上下文, context//应用程序上下文, environment//环境, listeners//运行监听器, applicationArguments//参数, printedBanner//Banner); //this=SpringApplication  ->
private void prepareContext(DefaultBootstrapContext bootstrapContext, ConfigurableApplicationContext context, ConfigurableEnvironment environment, SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments, Banner printedBanner) {
    context.setEnvironment(environment);
    this.postProcessApplicationContext(context); //对上下文进行处理 ->
    this.applyInitializers(context);// -> 
    listeners.contextPrepared(context); //监听器对应用程序上下文进行准备 
    bootstrapContext.close(context); //将两者关联起来
    if (this.logStartupInfo) {
        this.logStartupInfo(context.getParent() == null);
        this.logStartupProfileInfo(context); //配置profile
    }
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); //获取BeanFactory 

beanFactory.registerSingleton("springApplicationArguments", applicationArguments);//注册单例 -> 
if (printedBanner != null) {
    beanFactory.registerSingleton("springBootBanner", printedBanner);
}
if (beanFactory instanceof DefaultListableBeanFactory) {
    ((DefaultListableBeanFactory)beanFactory).setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding); //定义是否运行overriding
}
if (this.lazyInitialization) {
    context.addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor());  //添加处理器
}
Set<Object> sources = this.getAllSources();
    Assert.notEmpty(sources, "Sources must not be empty");
    this.load(context, sources.toArray(new Object[0])); //按类型加载资源 上下文绑定资源
    listeners.contextLoaded(context); //监听器加载上下文
}
protected void postProcessApplicationContext(ConfigurableApplicationContext context) {
    if (this.beanNameGenerator != null) {
        context.getBeanFactory().registerSingleton("org.springframework.context.annotation.internalConfigurationBeanNameGenerator", 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(context.getEnvironment().getConversionService());
    }

}

//注册单例
public void registerSingleton(String beanName, Object singletonObject) throws IllegalStateException {
    Assert.notNull(beanName, "Bean name must not be null");
    Assert.notNull(singletonObject, "Singleton object must not be null");
    synchronized(this.singletonObjects) {
        Object oldObject = this.singletonObjects.get(beanName);
        if (oldObject != null) {
            throw new IllegalStateException("Could not register object [" + singletonObject + "] under bean name '" + beanName + "': there is already object [" + oldObject + "] bound");
        } else {
            this.addSingleton(beanName, singletonObject);//从工厂中移除Beanname,加入到存储单例的Map中 
        }
    }
}
//初始化器对上下文进行初始化
protected void applyInitializers(ConfigurableApplicationContext context) {
    Iterator var2 = this.getInitializers().iterator();

    while(var2.hasNext()) {
        ApplicationContextInitializer initializer = (ApplicationContextInitializer)var2.next();
        Class<?> requiredType = GenericTypeResolver.resolveTypeArgument(initializer.getClass(), ApplicationContextInitializer.class);
        Assert.isInstanceOf(requiredType, context, "Unable to call initializer.");
        initializer.initialize(context); //每个上下文初始化器对上下文进行初始化 可拓展 -> 
    }

}
void contextPrepared(ConfigurableApplicationContext context) {
    this.doWithListeners("spring.boot.application.context-prepared", (listener) -> {
        listener.contextPrepared(context); // ->
    });
}
private void doWithListeners(String stepName, Consumer<SpringApplicationRunListener> listenerAction) {
    this.doWithListeners(stepName, listenerAction, (Consumer)null); //->
}
private void doWithListeners(String stepName, Consumer<SpringApplicationRunListener> listenerAction, Consumer<StartupStep> stepAction) {
    StartupStep step = this.applicationStartup.start(stepName);
    this.listeners.forEach(listenerAction);
    if (stepAction != null) {
        stepAction.accept(step);
    }

    step.end();
}
public void contextPrepared(ConfigurableApplicationContext context) {
    this.initialMulticaster.multicastEvent(new ApplicationContextInitializedEvent(this.application, this.args, context) //新建一个应用程序上下文初始化事件);  //原始的事件执行器 广播事件 ->
}
public void multicastEvent(ApplicationEvent event) {
    this.multicastEvent(event, this.resolveDefaultEventType(event)); // ->
}

public void multicastEvent(final ApplicationEvent event  //应用程序, @Nullable ResolvableType eventType //程序类) {
        ResolvableType type = eventType != null ? eventType : this.resolveDefaultEventType(event); //解析事件类型(所属类)
        Executor executor = this.getTaskExecutor(); //事件执行器
        Iterator var5 = this.getApplicationListeners(event, type).iterator(); //所有可用的监听器

        while(var5.hasNext()) {
            ApplicationListener<?> listener = (ApplicationListener)var5.next();
            if (executor != null) {
                executor.execute(() -> {
                    this.invokeListener(listener, event); //唤醒监听器 -> doInvokeListener(listener,event) ->
                });
            } else {
                this.invokeListener(listener, event);
            }
        }

    }

private void doInvokeListener(ApplicationListener listener, ApplicationEvent event) {
        try {
            listener.onApplicationEvent(event);  //将事件放在监听器里 如:添加到保存事件的Map中
        } catch (ClassCastException var6) {
            String msg = var6.getMessage();
            if (msg != null && !this.matchesClassCastMessage(msg, event.getClass()) && (!(event instanceof PayloadApplicationEvent) || !this.matchesClassCastMessage(msg, ((PayloadApplicationEvent)event).getPayload().getClass()))) {
                throw var6;
            }

            Log loggerToUse = this.lazyLogger;
            if (loggerToUse == null) {
                loggerToUse = LogFactory.getLog(this.getClass());
                this.lazyLogger = loggerToUse;
            }

            if (loggerToUse.isTraceEnabled()) {
                loggerToUse.trace("Non-matching event type for listener: " + listener, var6);
            }
        }

    }

public void registerSingleton(String beanName, Object singletonObject) throws IllegalStateException {
    super.registerSingleton(beanName, singletonObject);//注册单例:添加到存储MAP中
    this.updateManualSingletonNames((set) -> {
        set.add(beanName);
    }, (set) -> {
        return !this.beanDefinitionMap.containsKey(beanName);
    });
    this.clearByTypeCache();
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值