Spring - IoC 源码阅读笔记:AbstractApplicationContext - finishRefresh()

in Tech Java

前言

终于到 AbstractApplicationContext#refresh() 中的最后最后一个方法了。比较简单,就是清理下不需要的缓存,并推送刷新完成事件。

finishRefresh()

ServletWebServerApplicationContext#finishRefresh()

    @Override
    protected void finishRefresh() {
        super.finishRefresh();
        // 启动 Web 容器
        WebServer webServer = startWebServer();
        if (webServer != null) {
            publishEvent(new ServletWebServerInitializedEvent(webServer, this));
        }
    }

finishRefresh()

AbstractApplicationContext#finishRefresh()

    protected void finishRefresh() {
        // Clear context-level resource caches (such as ASM metadata from scanning).
        // 清除资源缓存
        clearResourceCaches();

        // Initialize lifecycle processor for this context.
        // 为此上下文初始化生命周期处理器
        initLifecycleProcessor();

        // Propagate refresh to lifecycle processor first.
        // 首先将刷新完毕事件传播到生命周期处理器
        getLifecycleProcessor().onRefresh();

        // Publish the final event.
        // 推送上下文刷新完毕事件到相应的监听器
        publishEvent(new ContextRefreshedEvent(this));

        // Participate in LiveBeansView MBean, if active.
        LiveBeansView.registerApplicationContext(this);
    }

initLifecycleProcessor() 方法

    protected void initLifecycleProcessor() {
        ConfigurableListableBeanFactory beanFactory = getBeanFactory();
        // BeanFactory 如果存在生命周期处理器,则直接赋值
        if (beanFactory.containsLocalBean(LIFECYCLE_PROCESSOR_BEAN_NAME)) {
            this.lifecycleProcessor =
                    beanFactory.getBean(LIFECYCLE_PROCESSOR_BEAN_NAME, LifecycleProcessor.class);
            if (logger.isTraceEnabled()) {
                logger.trace("Using LifecycleProcessor [" + this.lifecycleProcessor + "]");
            }
        }   
        // 否则,使用 DefaultLifecycleProcessor
        else {
            DefaultLifecycleProcessor defaultProcessor = new DefaultLifecycleProcessor();
            defaultProcessor.setBeanFactory(beanFactory);
            this.lifecycleProcessor = defaultProcessor;
            beanFactory.registerSingleton(LIFECYCLE_PROCESSOR_BEAN_NAME, this.lifecycleProcessor);
            if (logger.isTraceEnabled()) {
                logger.trace("No '" + LIFECYCLE_PROCESSOR_BEAN_NAME + "' bean, using " +
                        "[" + this.lifecycleProcessor.getClass().getSimpleName() + "]");
            }
        }
    }

onRefresh() 方法

DefaultLifecycleProcessor#onRefresh

    @Override
    public void onRefresh() {
        startBeans(true);
        this.running = true;
    }
    private void startBeans(boolean autoStartupOnly) {
        Map<String, Lifecycle> lifecycleBeans = getLifecycleBeans();
        Map<Integer, LifecycleGroup> phases = new HashMap<>();
        // 按阶段值分组
        lifecycleBeans.forEach((beanName, bean) -> {
            if (!autoStartupOnly || (bean instanceof SmartLifecycle && ((SmartLifecycle) bean).isAutoStartup())) {
                // 获取bean的阶段值(如果没有实现Phased接口,则值为0)
                int phase = getPhase(bean);
                LifecycleGroup group = phases.get(phase);
                if (group == null) {
                    // 如果该阶段值的 LifecycleGroup 为 null,则新建一个
                    group = new LifecycleGroup(phase, this.timeoutPerShutdownPhase, lifecycleBeans, autoStartupOnly);
                    phases.put(phase, group);
                }
                // 将 bean 添加到该 LifecycleGroup
                group.add(beanName, bean);
            }
        });
        if (!phases.isEmpty()) { 
            List<Integer> keys = new ArrayList<>(phases.keySet());
            // 按阶段值顺序,调用LifecycleGroup中的所有Lifecycle的start方法
            Collections.sort(keys);
            for (Integer key : keys){
                phases.get(key).start();
            }
        }
    }

publishEvent() 方法

    @Override
    public void publishEvent(ApplicationEvent event) {
        publishEvent(event, null);
    }
    protected void publishEvent(Object event, @Nullable ResolvableType eventType) {
        Assert.notNull(event, "Event must not be null");

        // Decorate event as an ApplicationEvent if necessary
        // 如有必要,将事件装饰为ApplicationEvent
        ApplicationEvent applicationEvent;
        if (event instanceof ApplicationEvent) {
            applicationEvent = (ApplicationEvent) event;
        }
        else {
            applicationEvent = new PayloadApplicationEvent<>(this, event);
            if (eventType == null) {
                eventType = ((PayloadApplicationEvent<?>) applicationEvent).getResolvableType();
            }
        }

        // Multicast right now if possible - or lazily once the multicaster is initialized
        // 使用事件广播器广播事件到相应的监听器
        if (this.earlyApplicationEvents != null) {
            this.earlyApplicationEvents.add(applicationEvent);
        }
        else {
            getApplicationEventMulticaster().multicastEvent(applicationEvent, eventType);
        }

        // Publish event via parent context as well...
        // 同样的,通过parent发布事件......
        if (this.parent != null) {
            if (this.parent instanceof AbstractApplicationContext) {
                ((AbstractApplicationContext) this.parent).publishEvent(event, eventType);
            }
            else {
                this.parent.publishEvent(event);
            }
        }
    }

总结

到这里,SpringBoot 中整个 IoC 容器启动的核心流程就完成啦!但是,还是存在未解之谜。比如,AOP、MVC 与 IoC 是如何实现交互的? 自动配置原理是什么?