美文网首页Spring boot
SpringBoot分析之启动原理-AbstractApplic

SpringBoot分析之启动原理-AbstractApplic

作者: 三也视界 | 来源:发表于2020-11-24 10:42 被阅读0次

    Spring初始化Ioc容器很重要的一个方法是由ApplicationContext子接口ConfigurableApplicationContext提供的refresh(),这个方法的作用是创建加载Spring容器配置(包括.xml配置,property文件和数据库模式等)

    本文主要是整体启动流程请查看springboot原理(核心原理、启动流程、执行流程)中的11. 调用ApplicationContext的refresh()方法,装配context beanfactory等非常重要的核心组件的源码分析:SpringBoot分析之启动原理-AbstractApplicationContext#refresh()

    本系列源码都是基于spring-4.3.8版本之上,其他版本略有差异,但总体的核心思想相同。同时,为了使贴出的源代码尽可能的紧凑,可能会删去一些异常捕获、日志输出等代码。若文中存在纰漏错误,欢迎指正。

        public void refresh() throws BeansException, IllegalStateException {
            // 准备刷新上下文
            prepareRefresh();
     
            /**
             * 构建beanFactory,其实是构建DefaultListableBeanFactory,
             * 这是一个非常重要的方法,spring对xml的解析就在这里进行,并将xml中的各种tag解析成具体的BeanDefinition,
             * 并注册到beanFactory。
             */
            ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
     
            /**
             * 准备初始化beanFactory,内部将一些系统bean注册到beanFactory, 
             * 如用于读取配置文件的StandardEnvironment
             */
            prepareBeanFactory(beanFactory);
     
            // 用于添加一些BeanPostProcessor,并注册一些内置的objectFactory
            postProcessBeanFactory(beanFactory);
     
            // 排序并执行所有的BeanFactoryPostProcessor、BeanDefinitionRegistryPostProcessor
            invokeBeanFactoryPostProcessors(beanFactory);
     
            // 排序并注册BeanPostProcessor,BeanPostProcessor作用是用于拦截Bean的创建
            registerBeanPostProcessors(beanFactory);
     
            // 初始化MessageSource
            initMessageSource();
     
            // 初始化ApplicationEventMulticaster
            initApplicationEventMulticaster();
     
            // 初始化其他的特殊bean
            onRefresh();
     
            // 检查、注册监听器
            registerListeners();
     
            // 实例化所有非延迟加载的单例Bean
            finishBeanFactoryInitialization(beanFactory);
     
            // 主要是一些生命周期相关组件的功能
            finishRefresh();
        }
    
    • prepareRefresh

        protected void prepareRefresh() {
            this.startupDate = System.currentTimeMillis();
            this.closed.set(false);
            this.active.set(true);
     
            if (logger.isInfoEnabled()) {
                logger.info("Refreshing " + this);
            }
     
            // Initialize any placeholder property sources in the context environment
            initPropertySources();
     
            // Validate that all properties marked as required are resolvable
            // see ConfigurablePropertyResolver#setRequiredProperties
            getEnvironment().validateRequiredProperties();
     
            // Allow for the collection of early ApplicationEvents,
            // to be published once the multicaster is available...
            this.earlyApplicationEvents = new LinkedHashSet<ApplicationEvent>();
        }
    
    • obtainFreshBeanFactory

        protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
            /**
             * 该方法主要做了两件事 
             * 1、创建核心的bean工厂-DefaultListableBeanFactory
             * 2、开始加载配置文件并注册bean,如:ioc容器的xml或@Configuration注解启动的类
             */
            refreshBeanFactory();
            // 其实只是简单的获取了上面创建的DefaultListableBeanFactory而已
            ConfigurableListableBeanFactory beanFactory = getBeanFactory();
            if (logger.isDebugEnabled()) {
                logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
            }
            return beanFactory;
        }
    

    refreshBeanFactory方法在AbstractApplicationContext中只是一个抽象方法,这里就以使用相对频繁的子类AbstractRefreshableApplicationContext为例。

        protected final void refreshBeanFactory() throws BeansException {
            // 若已存在bean工厂,则先销毁
            if (hasBeanFactory()) {
                destroyBeans();
                closeBeanFactory();
            }
            try {
                // 创建bean工厂,即DefaultListableBeanFactory,若存在父级beanFactory也会设置到自身的parentBeanFactory中
                DefaultListableBeanFactory beanFactory = createBeanFactory();
                beanFactory.setSerializationId(getId());
                /**
                 * 设置两个变量到当前beanFactory
                 * allowBeanDefinitionOverriding-允许BeanDefinition被覆盖,若为false,则存在相同的beanName会直接抛出异常
                 * allowCircularReferences-允许BeanDefinition被循环引用,若为false,则若发生两个组件相互依赖时,会抛出异常
                 */
                customizeBeanFactory(beanFactory);
                /**
                 * 这是一个抽象方法,用于加载BeanDefinition,根据不同的子ApplicationContext实现可以以不同形式注册组件 如:
                 * xml启动以XmlWebApplicationContext进行逐个加载ioc的各个xml
                 * 注解启动以AnnotationConfigWebApplicationContext进行逐个加载含有@Component注解的组件
                 */
                loadBeanDefinitions(beanFactory);
                synchronized (this.beanFactoryMonitor) {
                    this.beanFactory = beanFactory;
                }
            } catch (IOException ex) {
                throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(),
                        ex);
            }
        }
    
    • prepareBeanFactory

        protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
            // 给beanFactory设置类加载器
            beanFactory.setBeanClassLoader(getClassLoader());
            // 设置EL表达式解析器(很多地方会使用到,如springMvc解析请求入参、@Autowired、@Resource等注解的注入参数等)
            beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
            // 添加属性
            beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
     
            /**
             * 设置ApplicationContextAwareProcessor,
             * 用于在bean实例化时,前置调用ApplicationContextAware、EnvironmentAware等Aware接口实现,以注入对应的值
             */
            beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
            /**
             * <a href="https://www.jianshu.com/p/3c7e0608ff1f">具体作用可参考</a>
             * 将刚刚在前置处理中触发的六个Aware接口加入到ignoredDependencyInterfaces
             * 凡加入ignoredDependencyInterfaces的类,都不会进行依赖检查或自动装配
             */
            beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
            beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
            beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
            beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
            beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
            beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
     
            /**
             * 将以下四个接口(以key-依赖类型,value-实际值的方式)注册到resolvableDependencies,
             * 被加入resolvableDependencies的类可以@Autowired、@Resource、@Injected或@Value的方式注入的其他的bean,
             * 同时,若注入的类型为ObjectFactory的实现时,自动注入的注解将会注入ObjectFactory#getObject的对象
             */
            beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
            beanFactory.registerResolvableDependency(ResourceLoader.class, this);
            beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
            beanFactory.registerResolvableDependency(ApplicationContext.class, this);
     
            beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
     
            // 若没有手动添加过【loadTimeWeaver】,则将默认注册单例LoadTimeWeaverAwareProcessor到单例beanFactory
            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】,则将默认注册单例StandardEnvironment到单例beanFactory,
             * 可用于解析xml中的el表达式、注入@Value注解修饰的变量等
             */
            if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
                beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
            }
            // 若没有手动添加过【systemProperties】,则将默认注册单例System#getProperties(与jvm相关的变量)即系统环境到单例beanFactory
            if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
                beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
            }
            // 若没有手动添加过【systemEnvironment】,则将默认注册单例System#getenv(即系统环境变量)到单例beanFactory
            if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
                beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
            }
        }
    
    • postProcessBeanFactory

        protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
            /**
             * 添加ServletContextAwareProcessor,用于给自定义组件注入ServletContext、ServletConfig
             * 需要注意的是内部的beanPostProcessors是一个ArrayList,所以其内部是有序的, 按照添加顺序进行逐个执行
             */
            beanFactory.addBeanPostProcessor(new ServletContextAwareProcessor(this.servletContext, this.servletConfig));
            beanFactory.ignoreDependencyInterface(ServletContextAware.class);
            beanFactory.ignoreDependencyInterface(ServletConfigAware.class);
     
            /**
             * 注册web组件,如ServletRequest、ServletResponse、HttpSession等,
             * 统一添加到DefaultListableBeanFactory#resolvableDependencies,
             */
            WebApplicationContextUtils.registerWebApplicationScopes(beanFactory, this.servletContext);
            // 注册一些环境相关的单例bean到DefaultListableBeanFactory
            WebApplicationContextUtils.registerEnvironmentBeans(beanFactory, this.servletContext, this.servletConfig);
        }
    
        public static void registerWebApplicationScopes(ConfigurableListableBeanFactory beanFactory, ServletContext sc) {
            // 分别注册三个域,用于获取每个域对应的bean时使用
            beanFactory.registerScope(WebApplicationContext.SCOPE_REQUEST, new RequestScope());
            beanFactory.registerScope(WebApplicationContext.SCOPE_SESSION, new SessionScope(false));
            beanFactory.registerScope(WebApplicationContext.SCOPE_GLOBAL_SESSION, new SessionScope(true));
            if (sc != null) {
                ServletContextScope appScope = new ServletContextScope(sc);
                beanFactory.registerScope(WebApplicationContext.SCOPE_APPLICATION, appScope);
                // Register as ServletContext attribute, for ContextCleanupListener to detect it.
                sc.setAttribute(ServletContextScope.class.getName(), appScope);
            }
     
            /**
             * 注册ServletRequest、ServletResponse等以及对应的objectFactory到DefaultListableBeanFactory
             * 如SpringMvc的Controller在实例变量中注入Request、Response就是依靠这里的objectFactory获取线程变量实现的
             */
            beanFactory.registerResolvableDependency(ServletRequest.class, new RequestObjectFactory());
            beanFactory.registerResolvableDependency(ServletResponse.class, new ResponseObjectFactory());
            beanFactory.registerResolvableDependency(HttpSession.class, new SessionObjectFactory());
            beanFactory.registerResolvableDependency(WebRequest.class, new WebRequestObjectFactory());
            if (jsfPresent) {
                FacesDependencyRegistrar.registerFacesDependencies(beanFactory);
            }
        }
    
    • invokeBeanFactoryPostProcessors

        protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
            // 执行所有的BeanFactoryPostProcessor、BeanDefinitionRegistryPostProcessor
            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()));
            }
        }
    
        public static void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory,
                List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
     
            /**
             * 整个方法比较长,整体思路如下:
             * 1、先分类并排序后执行BeanDefinitionRegistryPostProcessor
             * 2、然后执行BeanFactoryPostProcessor
             */
            Set<String> processedBeans = new HashSet<String>();
     
            /**
             * 一般而言,beanFactory都是能转化成BeanDefinitionRegistry
             * DefaultListableBeanFactory就实现了BeanDefinitionRegistry
             */
            if (beanFactory instanceof BeanDefinitionRegistry) {
                BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
                List<BeanFactoryPostProcessor> regularPostProcessors = new LinkedList<BeanFactoryPostProcessor>();
                List<BeanDefinitionRegistryPostProcessor> registryPostProcessors = new LinkedList<BeanDefinitionRegistryPostProcessor>();
     
                /**
                 * 开始对所有beanFactoryPostProcessors进行分类
                 * 若能转换为BeanDefinitionRegistryPostProcessor则加入registryPostProcessors,
                 * 否则加入regularPostProcessors。
                 */
                for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
                    if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
                        BeanDefinitionRegistryPostProcessor registryPostProcessor = (BeanDefinitionRegistryPostProcessor) postProcessor;
                        registryPostProcessor.postProcessBeanDefinitionRegistry(registry);
                        registryPostProcessors.add(registryPostProcessor);
                    } else {
                        regularPostProcessors.add(postProcessor);
                    }
                }
     
                /**
                 * 从beanFactory中获取所有实现了BeanDefinitionRegistryPostProcessor的bean
                 */
                String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class,
                        true, false);
     
                /**
                 * 1、开始分类整理这些BeanDefinitionRegistryPostProcessor,
                 * 优先获取实现了PriorityOrdered的bean,并排序后逐个执行
                 */
                List<BeanDefinitionRegistryPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanDefinitionRegistryPostProcessor>();
                for (String ppName : postProcessorNames) {
                    if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
                        priorityOrderedPostProcessors
                                .add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                        processedBeans.add(ppName);
                    }
                }
                sortPostProcessors(beanFactory, priorityOrderedPostProcessors);
                registryPostProcessors.addAll(priorityOrderedPostProcessors);
                invokeBeanDefinitionRegistryPostProcessors(priorityOrderedPostProcessors, registry);
     
                /**
                 * 2、重新分类整理这些BeanDefinitionRegistryPostProcessor, 这次获取实现了Ordered的bean,并排序后逐个执行
                 */
                postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true,
                        false);
                List<BeanDefinitionRegistryPostProcessor> orderedPostProcessors = new ArrayList<BeanDefinitionRegistryPostProcessor>();
                for (String ppName : postProcessorNames) {
                    if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
                        orderedPostProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                        processedBeans.add(ppName);
                    }
                }
                sortPostProcessors(beanFactory, orderedPostProcessors);
                registryPostProcessors.addAll(orderedPostProcessors);
                invokeBeanDefinitionRegistryPostProcessors(orderedPostProcessors, registry);
     
                /**
                 * 3、再一次获取这些这些BeanDefinitionRegistryPostProcessor,并逐个执行
                 */
                boolean reiterate = true;
                while (reiterate) {
                    reiterate = false;
                    postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true,
                            false);
                    for (String ppName : postProcessorNames) {
                        if (!processedBeans.contains(ppName)) {
                            BeanDefinitionRegistryPostProcessor pp = beanFactory.getBean(ppName,
                                    BeanDefinitionRegistryPostProcessor.class);
                            registryPostProcessors.add(pp);
                            processedBeans.add(ppName);
                            pp.postProcessBeanDefinitionRegistry(registry);
                            reiterate = true;
                        }
                    }
                }
     
                // 开始分类执行BeanFactoryPostProcessor
                invokeBeanFactoryPostProcessors(registryPostProcessors, beanFactory);
                invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
            }
     
            else {
                // 对没有实现BeanDefinitionRegistry的beanFactory,直接不分类,粗暴执行这些BeanFactoryPostProcessor
                invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
            }
     
            // 从beanFactory中获取所有实现了BeanFactoryPostProcessor的bean
            String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
     
            // 开始分类,分类原则与BeanDefinitionRegistryPostProcessor相同
            List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
            List<String> orderedPostProcessorNames = new ArrayList<String>();
            List<String> nonOrderedPostProcessorNames = new ArrayList<String>();
            for (String ppName : postProcessorNames) {
                if (processedBeans.contains(ppName)) {
                    // skip - already processed in first phase above
                } else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
                    priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
                } else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
                    orderedPostProcessorNames.add(ppName);
                } else {
                    nonOrderedPostProcessorNames.add(ppName);
                }
            }
     
            // 首先,执行实现了PriorityOrdered的BeanFactoryPostProcessor
            sortPostProcessors(beanFactory, priorityOrderedPostProcessors);
            invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
     
            // 然后,执行实现了Ordered的BeanFactoryPostProcessor
            List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
            for (String postProcessorName : orderedPostProcessorNames) {
                orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
            }
            sortPostProcessors(beanFactory, orderedPostProcessors);
            invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
     
            // 最后,执行剩余的BeanFactoryPostProcessor
            List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
            for (String postProcessorName : nonOrderedPostProcessorNames) {
                nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
            }
            invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
     
            beanFactory.clearMetadataCache();
        }
    
    • registerBeanPostProcessors

        protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
            PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
        }
    
        public static void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory,
                AbstractApplicationContext applicationContext) {
     
            /**
             * 若理解了上一步的invokeBeanFactoryPostProcessors, 那这里就理解起来就相当容易了,
             * 唯一有区别的是由于这里是注册BeanPostProcessor,而BeanPostProcessor是在每个bean实例化前后调用的,
             * 所以这里只是单独的注册到beanFactory,并没有逐个执行
             */
            // 从beanFactory中获取所有BeanPostProcessor的beanName
            String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
     
            int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
            beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
     
            // 开始根据beanName遍历BeanPostProcessor,并按照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)) {
                    BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
                    priorityOrderedPostProcessors.add(pp);
                    if (pp instanceof MergedBeanDefinitionPostProcessor) {
                        internalPostProcessors.add(pp);
                    }
                } else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
                    orderedPostProcessorNames.add(ppName);
                } else {
                    nonOrderedPostProcessorNames.add(ppName);
                }
            }
     
            // 1、排序并注册实现了PriorityOrdered的BeanPostProcessor
            sortPostProcessors(beanFactory, priorityOrderedPostProcessors);
            registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
     
            // 2、排序并注册实现了Ordered的BeanPostProcessor
            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(beanFactory, orderedPostProcessors);
            registerBeanPostProcessors(beanFactory, orderedPostProcessors);
     
            // 3、排序并注册了剩余的BeanPostProcessor
            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);
     
            // 4、排序并注册了实现了MergedBeanDefinitionPostProcessor的BeanPostProcessor
            sortPostProcessors(beanFactory, internalPostProcessors);
            registerBeanPostProcessors(beanFactory, internalPostProcessors);
     
            /**
             * 经过上述四个步骤后,所有的BeanPostProcessor就以有序的形式保存到了beanFactory中
             * 在每个bean实例化时,就能按照这个有序的顺序进行逐个执行BeanPostProcessor的前后置方法了
             */
     
            beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
        }
    
    • initMessageSource

        protected void initMessageSource() {
            ConfigurableListableBeanFactory beanFactory = getBeanFactory();
            /**
             * 从beanFactory中查找messageSource,
             * 若没有则会实例化一个DelegatingMessageSource并注册到beanFactory
             */
            if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
                this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
                if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
                    HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
                    if (hms.getParentMessageSource() == null) {
                        hms.setParentMessageSource(getInternalParentMessageSource());
                    }
                }
            } else {
                DelegatingMessageSource dms = new DelegatingMessageSource();
                dms.setParentMessageSource(getInternalParentMessageSource());
                this.messageSource = dms;
                beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
            }
        }
    
    • initApplicationEventMulticaster

        protected void initApplicationEventMulticaster() {
            ConfigurableListableBeanFactory beanFactory = getBeanFactory();
            /**
             * 从beanFactory中查找applicationEventMulticaster,
             * 若没有则会初始化一个SimpleApplicationEventMulticaster并注册到beanFactory
             */
            if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
                this.applicationEventMulticaster = beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME,
                        ApplicationEventMulticaster.class);
            } else {
                this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
                beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
            }
        }
    
    • onRefresh

    该方法在AbstractApplicationContext中是一个抽象方法

         protected void onRefresh() throws BeansException {
            // For subclasses: do nothing by default.
        }
    

    查看了若干个子类,如AbstractRefreshableWebApplicationContext、GenericWebApplicationContext等,发现其实现中基本都是做的同一件事,初始化了一个themeSource。

        protected void onRefresh() {
            this.themeSource = UiApplicationContextUtils.initThemeSource(this);
        }
    

    但是SpringBoot中onRefresh就非常重要了,内嵌的tomcat容器就是通过该方法创建的。

    • registerListeners

        protected void registerListeners() {
            // 首先将所有已添加的监听器绑定到事件广播器中
            for (ApplicationListener<?> listener : getApplicationListeners()) {
                getApplicationEventMulticaster().addApplicationListener(listener);
            }
     
            // 然后再从beanFactory中获取所有ApplicationListener,将beanName绑定到事件广播器中
            String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
            for (String listenerBeanName : listenerBeanNames) {
                getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
            }
     
            // 判断早期的应用事件,若不为空,则调用事件广播器逐个进行广播
            Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
            this.earlyApplicationEvents = null;
            if (earlyEventsToProcess != null) {
                for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
                    getApplicationEventMulticaster().multicastEvent(earlyEvent);
                }
            }
        }
    
    • finishBeanFactoryInitialization

        protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
            /**
             * 如果conversionService存在的话,则实例化conversionService,
             * 这是一个用于类型转换的组件,不论是ioc的依赖注入还是springmvc的入参绑定都可能会用到该组件
             */
            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));
            }
     
            /**
             * 若beanFactory内没有内嵌的值解析器,则默认添加一个内置解析器,但是该内置解析器只能处理系统变量的解析,
             * 但是若配置了PropertySourcesPlaceholderConfigurer,
             * 则会另加入一个读取对应配置文件的值解析器,则默认值解析器就不会再添加到容器了
             * 同时需要注意的是这个值解析器是和当前容器绑定的,也就是说子容器是无法获取到父容器的值解析器的,
             * 这也就是为什么在springmvc的controller中使用@Value是无法注入配置文件中的值的
             */
            if (!beanFactory.hasEmbeddedValueResolver()) {
                beanFactory.addEmbeddedValueResolver(new StringValueResolver() {
                    @Override
                    public String resolveStringValue(String strVal) {
                        return getEnvironment().resolvePlaceholders(strVal);
                    }
                });
            }
     
            // 提早实例化所有LoadTimeWeaverAware实现
            String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
            for (String weaverAwareName : weaverAwareNames) {
                getBean(weaverAwareName);
            }
     
            // 禁止在类型匹配中使用临时的类加载器
            beanFactory.setTempClassLoader(null);
     
            /**
             * 允许缓存beanDefinition元数据,
             * 实则是将所有beanDefinitionNames转化成了String数组,并存储到frozenBeanDefinitionNames中
             */
            beanFactory.freezeConfiguration();
     
            /**
             * 开始实例化所有非延迟加载的单例bean 也就是说会对容器内所有非抽象、非延迟加载的单例bean进行逐个实例化
             */
            beanFactory.preInstantiateSingletons();
        }
    
    • finishRefresh

    相关文章

      网友评论

        本文标题:SpringBoot分析之启动原理-AbstractApplic

        本文链接:https://www.haomeiwen.com/subject/exxzbktx.html