热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Spring系列(三):SpringIoC源码解析

一、Spring容器类继承图二、容器前期准备IoC源码解析入口:调用构造函数AnnotationConfigApplicationContext调用this(),会默认先调用父类的

一、Spring容器类继承图

二、容器前期准备

  IoC源码解析入口:

/**
 * @desc: ioc原理解析 启动
 * @author: toby
 * @date: 2019/7/22 22:20
 */
public class PrincipleMain {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(PrincipleConfig.class);
    }
}

  调用构造函数AnnotationConfigApplicationContext

  调用this(),会默认先调用父类的无参构造函数,为ApplicationContext上下文对象初始beanFactory = new DefaultListableBeanFactory()

  在调用当前类的this(),也就是调用自己的无参构造函数:

    进到创建注解模式下的Bean定义读取器:

  org.springframework.context.annotation.AnnotationConfigUtils#registerAnnotationConfigProcessors(org.springframework.beans.factory.support.BeanDefinitionRegistry, java.lang.Object) 主要是注册Spring自身的一些后置处理器

public static Set registerAnnotationConfigProcessors(
            BeanDefinitionRegistry registry, @Nullable Object source) {

        DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
        if (beanFactory != null) {
            if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {
                beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
            }
            if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {
                beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
            }
        }

        Set beanDefs = new LinkedHashSet<>(8);

        /**
         * 为我们容器中注册解析主配置类的后置处理器ConfigurationClassPostProcessor
         * beanName = org.springframework.context.annotation.internalConfigurationAnnotationProcessor
         */
        if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
            RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
            def.setSource(source);
            beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
        }

        /**
         * 为我们容器中注册处理@Autowired注解的Bean的后置处理器AutowiredAnnotationBeanPostProcessor
         * beanName = org.springframework.context.annotation.internalAutowiredAnnotationProcessor
         */
        if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
            RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);
            def.setSource(source);
            beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
        }

        /**
         * 为我们容器中注册处理@Required属性注解的Bean后置处理器RequiredAnnotationBeanPostProcessor
         * beanName = org.springframework.context.annotation.internalRequiredAnnotationProcessor
         */
        if (!registry.containsBeanDefinition(REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
            RootBeanDefinition def = new RootBeanDefinition(RequiredAnnotationBeanPostProcessor.class);
            def.setSource(source);
            beanDefs.add(registerPostProcessor(registry, def, REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
        }

        /**
         * 为我们容器注册处理JSR规范注解的Bean后置处理器CommonAnnotationBeanPostProcessor
         * beanName = org.springframework.context.annotation.internalCommonAnnotationProcessor
         */
        if (jsr250Present && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) {
            RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);
            def.setSource(source);
            beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
        }

        /**
         * 为我们容器注册处理jpa的Bean的后置处理器org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor
         */
        if (jpaPresent && !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) {
            RootBeanDefinition def = new RootBeanDefinition();
            try {
                def.setBeanClass(ClassUtils.forName(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME,
                        AnnotationConfigUtils.class.getClassLoader()));
            }
            catch (ClassNotFoundException ex) {
                throw new IllegalStateException(
                        "Cannot load optional framework class: " + PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, ex);
            }
            def.setSource(source);
            beanDefs.add(registerPostProcessor(registry, def, PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME));
        }

        /**
         * 处理监听方法的注解解析器EventListenerMethodProcessor
         */
        if (!registry.containsBeanDefinition(EVENT_LISTENER_PROCESSOR_BEAN_NAME)) {
            RootBeanDefinition def = new RootBeanDefinition(EventListenerMethodProcessor.class);
            def.setSource(source);
            beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_PROCESSOR_BEAN_NAME));
        }

        /**
         * 注册事件监听器工厂
         */
        if (!registry.containsBeanDefinition(EVENT_LISTENER_FACTORY_BEAN_NAME)) {
            RootBeanDefinition def = new RootBeanDefinition(DefaultEventListenerFactory.class);
            def.setSource(source);
            beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_FACTORY_BEAN_NAME));
        }

        return beanDefs;
    }

  读取器初始化完成后,Spring的容器的Bean的定义信息就有Spring自身的一些后置处理器了,Debug如下:

  读取器初始化完成后,接下来初始化ClassPath下的Bean定义扫描器:

     org.springframework.context.annotation.ClassPathBeanDefinitionScanner#ClassPathBeanDefinitionScanner(org.springframework.beans.factory.support.BeanDefinitionRegistry, boolean, org.springframework.core.env.Environment, org.springframework.core.io.ResourceLoader) 类路径下的Bean定义扫描

 

   org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider#registerDefaultFilters 注入默认的Filter

protected void registerDefaultFilters() {
        this.includeFilters.add(new AnnotationTypeFilter(Component.class));
        ClassLoader cl = ClassPathScanningCandidateComponentProvider.class.getClassLoader();
        try {
            this.includeFilters.add(new AnnotationTypeFilter(
                    ((Classextends Annotation>) ClassUtils.forName("javax.annotation.ManagedBean", cl)), false));
            logger.debug("JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning");
        }
        catch (ClassNotFoundException ex) {
            // JSR-250 1.1 API (as included in Java EE 6) not available - simply skip.
        }
        try {
            this.includeFilters.add(new AnnotationTypeFilter(
                    ((Classextends Annotation>) ClassUtils.forName("javax.inject.Named", cl)), false));
            logger.debug("JSR-330 'javax.inject.Named' annotation found and supported for component scanning");
        }
        catch (ClassNotFoundException ex) {
            // JSR-330 API not available - simply skip.
        }
    }

  这里需要注意的是为什么new AnnotationTypeFilter(Component.class)就可以处理@Repository,@Service,@Controller这3个注解,原因如下:

  自此前期准备工作完成

三、org.springframework.context.support.AbstractApplicationContext#refresh 12大步

public void refresh() throws BeansException, IllegalStateException {
        synchronized (this.startupShutdownMonitor) {
            //1:准备刷新上下文环境
            prepareRefresh();

            //2:获取初始化Bean工厂
            ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

            //3:对bean工厂进行填充属性
            prepareBeanFactory(beanFactory);

            try {
                //4:Spring开放接口 留给子类去实现该接口
                postProcessBeanFactory(beanFactory);

                //5:调用我们的bean工厂的后置处理器
                invokeBeanFactoryPostProcessors(beanFactory);

                //6:注册我们bean后置处理器
                registerBeanPostProcessors(beanFactory);

                //7:初始化国际化资源处理器
                initMessageSource();

                //8:初始化事件多播器
                initApplicationEventMulticaster();

                //9:这个方法同样也是留个子类实现,其中springboot也是从这个方法进行tomcat的启动
                onRefresh();

                //10:把我们的事件监听器注册到多播器上
                registerListeners();

                //11:实例化所有的非懒加载的单实例bean
                finishBeanFactoryInitialization(beanFactory);

                //12:最后刷新容器 发布刷新事件(Spring cloud eureka也是从这里启动的)
                finishRefresh();
            }

            catch (BeansException ex) {
                if (logger.isWarnEnabled()) {
                    logger.warn("Exception encountered during context initialization - " +
                            "cancelling refresh attempt: " + ex);
                }

                // Destroy already created singletons to avoid dangling resources.
                destroyBeans();

                // Reset 'active' flag.
                cancelRefresh(ex);

                // Propagate exception to caller.
                throw ex;
            }

            finally {
                // Reset common introspection caches in Spring's core, since we
                // might not ever need metadata for singleton beans anymore...
                resetCommonCaches();
            }
        }
    }

  第一步:prepareRefresh()

  准备刷新上下文环境:

protected void prepareRefresh() {
        // Switch to active.
        this.startupDate = System.currentTimeMillis();
        this.closed.set(false);
        this.active.set(true);

        if (logger.isInfoEnabled()) {
            logger.info("Refreshing " + this);
        }

        /**
         * 初始化上下文环境
         */
        initPropertySources();

        /**
         * 用来校验我们容器启动必须依赖的环境变量的值
         */
        getEnvironment().validateRequiredProperties();

        /**
         * 创建一个早期事件监听器对象
         */
        if (this.earlyApplicatiOnListeners== null) {
            this.earlyApplicatiOnListeners= new LinkedHashSet<>(this.applicationListeners);
        }
        else {
            // Reset local application listeners to pre-refresh state.
            this.applicationListeners.clear();
            this.applicationListeners.addAll(this.earlyApplicationListeners);
        }

        /**
         * 创建一个容器用于保存早期待发布的事件集合 什么是早期事件了?
         * 就是我们的事件监听器还没有注册到事件多播器上的时候都称为早期事件
         */
        this.earlyApplicatiOnEvents= new LinkedHashSet<>();
    }

  第二步:ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory() 

  获取初始化的Bean的工厂:

protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
        //刷新bean工厂()
        refreshBeanFactory();
        //返回之前容器准备工作的时候创建的的bean工厂也就是DefaultListableBeanFactory(很重要
        ConfigurableListableBeanFactory beanFactory = getBeanFactory();
        if (logger.isDebugEnabled()) {
            logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
        }
        return beanFactory;
    }

  org.springframework.context.support.GenericApplicationContext#refreshBeanFactory,注意只能刷一次

protected final void refreshBeanFactory() throws IllegalStateException {
        //由于BeanFactory只能刷新一次,多线程情况下可能导致线程安全问题,所有使用cas原子操作来保证
        if (!this.refreshed.compareAndSet(false, true)) {
            throw new IllegalStateException(
                    "GenericApplicationContext does not support multiple refresh attempts: just call 'refresh' once");
        }
        //指定Bean工厂的序列化Id
        this.beanFactory.setSerializationId(getId());
    }

   第三步:prepareBeanFactory(beanFactory)

  对bean工厂进行填充属性:

protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
        //设置bean工厂的类加载器为当前application应用上下文的加载器
        beanFactory.setBeanClassLoader(getClassLoader());
        //为bean工厂设置SPEL表达式解析器对象StandardBeanExpressionResolver
        beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
        //为我们的bean工厂设置了一个propertyEditor属性资源编辑器对象(用于后面的给bean对象赋值使用)
        beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
        //注册ApplicationContextAwareProcessor后置处理器用来处理ApplicationContextAware接口的回调方法
        beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
        /**
         * 当Spring将ApplicationContextAwareProcessor注册后,那么在invokeAwarelnterfaces方法中调用的Aware类已经不是普通的bean了 ,
         * 如ResourceLoaderAware、ApplicationEventPublisherAware、ApplicationContextAware等,那么当然需要在Spring做bean的依赖注入的时候忽略它们。
         * 这个就是ignoreDependencyInterface的作用
         */
        beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
        beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
        beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
        beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
        beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
        beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
        /**
         * 注册了依赖解析,例如当注册BeanFactory.class的解析依赖后,
         * 当bean的属性注入的时候,一旦检测到属性为BeanFactory类型便会将beanFactory的实例注入进去。
         */
        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));
        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()));
        }
        if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
            beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
        }
        if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
            beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
        }
        if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
            beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
        }
    }

  第四步:postProcessBeanFactory(beanFactory)

  Spring开放接口留给子类去实现该接口:主要用来改变BeanFactory比如给BeanFactory添加一些自己的BeanPostProcessor(Bean的后置处理器)

  第五步:invokeBeanFactoryPostProcessors(beanFactory)

  调用我们的bean工厂的后置处理器:详解见:Spring IoC源码解析之invokeBeanFactoryPostProcessors

  第六步:registerBeanPostProcessors(beanFactory)

  注册我们bean后置处理器:

org.springframework.context.support.PostProcessorRegistrationDelegate#registerBeanPostProcessors(org.springframework.beans.factory.config.ConfigurableListableBeanFactory, org.springframework.context.support.AbstractApplicationContext)

/**
     * 往容器中注册了我们的bean的后置处理器
     * bean的后置处理器在什么时候进行调用?在bean的生命周期中
     * @param beanFactory
     * @param applicationContext
     */
    public static void registerBeanPostProcessors(
            ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {

        //去容器中获取所有的BeanPostProcessor的bean名称
        String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);

        /**
         * beanFactory.getBeanPostProcessorCount()获取的是已经添加在beanFactory的beanPostProcessors集合中的
         * postProcessorNames.length  beanFactory工厂中BeanPostProcessor个数 +1 又注册了BeanPostProcessorChecker的后置处理器
         */
        int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
        beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

        /**
         * 按照BeanPostProcessor实现的优先级接口来分离我们的后置处理器
         */
        //保存实现了priorityOrdered接口的
        List priorityOrderedPostProcessors = new ArrayList<>();
        //容器内部的
        List internalPostProcessors = new ArrayList<>();
        //实现了我们ordered接口的
        List orderedPostProcessorNames = new ArrayList<>();
        //实现了我们任何优先级的
        List nOnOrderedPostProcessorNames= new ArrayList<>();
        //循环我们的bean定义(BeanPostProcessor)
        for (String ppName : postProcessorNames) {
            //若实现了PriorityOrdered接口的
            if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
                //显示的调用getBean流程创建bean的后置处理器
                BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
                //加入到集合中
                priorityOrderedPostProcessors.add(pp);
                //判断是否实现了MergedBeanDefinitionPostProcessor
                if (pp instanceof MergedBeanDefinitionPostProcessor) {
                    //加入到集合中
                    internalPostProcessors.add(pp);
                }
            }
            //判断是否实现了Ordered
            else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
                orderedPostProcessorNames.add(ppName);
            }
            else {
                nonOrderedPostProcessorNames.add(ppName);
            }
        }

        //把实现了priorityOrdered注册到容器中
        sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
        registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

        //处理实现Ordered的bean后置处理器
        List orderedPostProcessors = new ArrayList<>();
        for (String ppName : orderedPostProcessorNames) {
            //显示调用getBean方法
            BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
            //加入到集合中
            orderedPostProcessors.add(pp);
            //判断是否实现了MergedBeanDefinitionPostProcessor
            if (pp instanceof MergedBeanDefinitionPostProcessor) {
                //加入到集合中
                internalPostProcessors.add(pp);
            }
        }
        //排序并且注册我们实现了Order接口的后置处理器
        sortPostProcessors(orderedPostProcessors, beanFactory);
        registerBeanPostProcessors(beanFactory, orderedPostProcessors);

        // 实例化我们所有的非排序接口的
        List nOnOrderedPostProcessors= new ArrayList<>();
        for (String ppName : nonOrderedPostProcessorNames) {
            //显示调用
            BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
            nonOrderedPostProcessors.add(pp);
            //判断是否实现了MergedBeanDefinitionPostProcessor
            if (pp instanceof MergedBeanDefinitionPostProcessor) {
                internalPostProcessors.add(pp);
            }
        }
        //注册我们普通的没有实现任何排序接口的
        registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);

        //注册MergedBeanDefinitionPostProcessor类型的后置处理器
        sortPostProcessors(internalPostProcessors, beanFactory);
        registerBeanPostProcessors(beanFactory, internalPostProcessors);

        //注册ApplicationListenerDetector应用监听器探测器的后置处理器
        beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
    }

  第七步:initMessageSource()

  初始化国际化资源处理器:

/**
     * Initialize the MessageSource.
     * Use parent's if none defined in this context.
     */
    protected void initMessageSource() {
        ConfigurableListableBeanFactory beanFactory = getBeanFactory();
        if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
            this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
            // Make MessageSource aware of parent MessageSource.
            if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
                HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
                if (hms.getParentMessageSource() == null) {
                    // Only set parent context as parent MessageSource if no parent MessageSource
                    // registered already.
                    hms.setParentMessageSource(getInternalParentMessageSource());
                }
            }
            if (logger.isDebugEnabled()) {
                logger.debug("Using MessageSource [" + this.messageSource + "]");
            }
        }
        else {
            // Use empty MessageSource to be able to accept getMessage calls.
            DelegatingMessageSource dms = new DelegatingMessageSource();
            dms.setParentMessageSource(getInternalParentMessageSource());
            this.messageSource = dms;
            beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
            if (logger.isDebugEnabled()) {
                logger.debug("Unable to locate MessageSource with name '" + MESSAGE_SOURCE_BEAN_NAME +
                        "': using default [" + this.messageSource + "]");
            }
        }
    }

  第八步:initApplicationEventMulticaster()

  初始化事件多播器:

/**
     * 从bean工厂中获取或者直接显示的new一个事件多播器赋值给applicatoinContext对象的applicationEventMulticaster属性
     * 事件多播器采用典型的设计模式就是观察者模式 多播器作为的是一个被观察者
     * @see org.springframework.context.event.SimpleApplicationEventMulticaster
     */
    protected void initApplicationEventMulticaster() {
        //获取我们的bean工厂对象
        ConfigurableListableBeanFactory beanFactory = getBeanFactory();
        //判断容器中是否包含了applicationEventMulticaster事件多播器组件
        if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
            //直接显示的调用我们的getBean获取出来赋值给我们的applicationContext对象
            this.applicatiOnEventMulticaster=
                    beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
            if (logger.isDebugEnabled()) {
                logger.debug("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
            }
        }
        //容器中没有的话
        else {
            //直接new一个
            this.applicatiOnEventMulticaster= new SimpleApplicationEventMulticaster(beanFactory);
            //并且注入到容器中
            beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
            if (logger.isDebugEnabled()) {
                logger.debug("Unable to locate ApplicationEventMulticaster with name '" +
                        APPLICATION_EVENT_MULTICASTER_BEAN_NAME +
                        "': using default [" + this.applicationEventMulticaster + "]");
            }
        }
    }

  第九步:onRefresh()

  这个方法很重要同样也是留个子类实现,其中Spring Boot就是从这个方法进行tomcat的启动(后续讲Spring Boot的源码分析的时候会涉及到这块,比如:Spring容器的启动如何带动web容器tomcat的启动以及web容器tomcat的启动如何带动Spring容器的启动

  第十步:registerListeners()

  把我们的事件监听器注册到事件多播器上:

protected void registerListeners() {
        //获取容器中所有的监听器对象
        for (ApplicationListener listener : getApplicationListeners()) {
            //把监听器挨个的注册到我们的事件多播器上去
            getApplicationEventMulticaster().addApplicationListener(listener);
        }

        //获取bean定义中的监听器对象
        String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
        //把监听器的名称注册到我们的事件多播器上
        for (String listenerBeanName : listenerBeanNames) {
            getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
        }

        //在这里获取我们的早期事件
        Set earlyEventsToProcess = this.earlyApplicationEvents;
        this.earlyApplicatiOnEvents= null;
        if (earlyEventsToProcess != null) {
            //通过多播器进行播发早期事件
            for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
                getApplicationEventMulticaster().multicastEvent(earlyEvent);
            }
        }
    }

  如何发布事件,通过事件多播器方法:multicastEvent(ApplicationEvent event),进入方法

@Override
    public void multicastEvent(ApplicationEvent event) {
        multicastEvent(event, resolveDefaultEventType(event));
    }

  multicastEvent(event, resolveDefaultEventType(event))方法:

@Override
    public void multicastEvent(final ApplicationEvent event, @Nullable ResolvableType eventType) {
        ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event));
        //从事件多播器中获取出所有的监听器
        for (final ApplicationListener listener : getApplicationListeners(event, type)) {
            //判断多播器中是否支持异步多播的
            Executor executor = getTaskExecutor();
            if (executor != null) {
                //异步播发事件
                executor.execute(() -> invokeListener(listener, event));
            }
            else {//同步播发
                invokeListener(listener, event);
            }
        }
    }

  invokeListener(listener, event)方法:

/**
     * Invoke the given listener with the given event.
     * @param listener the ApplicationListener to invoke
     * @param event the current event to propagate
     * @since 4.1
     */
    protected void invokeListener(ApplicationListener listener, ApplicationEvent event) {
        ErrorHandler errorHandler = getErrorHandler();
        if (errorHandler != null) {
            try {
                doInvokeListener(listener, event);
            }
            catch (Throwable err) {
                errorHandler.handleError(err);
            }
        }
        else {
            doInvokeListener(listener, event);
        }
    }

  doInvokeListener(ApplicationListener listener, ApplicationEvent event) 方法(Spring有一个特点涉及到以do开头的方法都是真正干活的):

  第十一步:finishBeanFactoryInitialization(beanFactory)

   实例化所有的非懒加载的单实例bean:详解见:Spring IoC源码解析之getBean

  第十二步:finishRefresh()

  最后刷新容器发布刷新事件(Spring cloud eureka也是从这里启动的):

protected void finishRefresh() {

        //初始化生命周期处理器
        initLifecycleProcessor();

        //调用生命周期处理器的onRefresh方法
        getLifecycleProcessor().onRefresh();

        //发布ContextRefreshedEvent事件
        publishEvent(new ContextRefreshedEvent(this));

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

  ① 初始化生命周期处理器:initLifecycleProcessor()方法:

protected void initLifecycleProcessor() {
        //获取beanFactory工厂
        ConfigurableListableBeanFactory beanFactory = getBeanFactory();
        //判断容器中是否有lifecycleProcessor,有就直接从容器中拿
        if (beanFactory.containsLocalBean(LIFECYCLE_PROCESSOR_BEAN_NAME)) {
            this.lifecycleProcessor =
                    beanFactory.getBean(LIFECYCLE_PROCESSOR_BEAN_NAME, LifecycleProcessor.class);
            if (logger.isDebugEnabled()) {
                logger.debug("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.isDebugEnabled()) {
                logger.debug("Unable to locate LifecycleProcessor with name '" +
                        LIFECYCLE_PROCESSOR_BEAN_NAME +
                        "': using default [" + this.lifecycleProcessor + "]");
            }
        }
    }

  ② 调用生命周期处理器的onRefresh方法:getLifecycleProcessor().onRefresh():org.springframework.context.support.DefaultLifecycleProcessor#onRefresh:

@Override
    public void onRefresh() {
        startBeans(true);
        this.running = true;
    }

  startBeans(true)方法:org.springframework.context.support.DefaultLifecycleProcessor#startBeans:主要的功能是找到Spring容器的Lifecycle类型的Bean,然后调用start()去启动

private void startBeans(boolean autoStartupOnly) {
        Map lifecycleBeans = getLifecycleBeans();
        Map phases = new HashMap();
        for (Map.Entryextends Lifecycle> entry : lifecycleBeans.entrySet()) {
            Lifecycle bean = entry.getValue();
            if (!autoStartupOnly || (bean instanceof SmartLifecycle && ((SmartLifecycle) bean).isAutoStartup())) {
                int phase = getPhase(bean);
                LifecycleGroup group = phases.get(phase);
                if (group == null) {
                    group = new LifecycleGroup(phase, this.timeoutPerShutdownPhase, lifecycleBeans, autoStartupOnly);
                    phases.put(phase, group);
                }
                group.add(entry.getKey(), bean);
            }
        }
        if (!phases.isEmpty()) {
            List keys = new ArrayList(phases.keySet());
            Collections.sort(keys);
            for (Integer key : keys) {
                phases.get(key).start();
            }
        }
    }

  start()方法:

  doStart(this.lifecycleBeans, member.name, this.autoStartupOnly)方法:

private void doStart(Mapextends Lifecycle> lifecycleBeans, String beanName, boolean autoStartupOnly) {
        Lifecycle bean = lifecycleBeans.remove(beanName);
        if (bean != null && bean != this) {
            String[] dependenciesForBean = getBeanFactory().getDependenciesForBean(beanName);
            for (String dependency : dependenciesForBean) {
                doStart(lifecycleBeans, dependency, autoStartupOnly);
            }
            //bean不在运行中并且(autoStartupOnly=false 或者 不是SmartLifecycle类型 或者 isAutoStartup() = true)
            if (!bean.isRunning() &&
                    (!autoStartupOnly || !(bean instanceof SmartLifecycle) || ((SmartLifecycle) bean).isAutoStartup())) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Starting bean '" + beanName + "' of type [" + bean.getClass().getName() + "]");
                }
                try {
                    //调用生命周期Lifecycle Bean的start()方法
                    bean.start();
                }
                catch (Throwable ex) {
                    throw new ApplicationContextException("Failed to start bean '" + beanName + "'", ex);
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("Successfully started bean '" + beanName + "'");
                }
            }
        }
    }

  ③ 发布ContextRefreshedEvent事件:主要就是调用前面第八步创建的事件多播器的发布事件方法getApplicationEventMulticaster().multicastEvent(applicationEvent, eventType):

protected void publishEvent(Object event, ResolvableType eventType) {
        Assert.notNull(event, "Event must not be null");
        if (logger.isTraceEnabled()) {
            logger.trace("Publishing event in " + getDisplayName() + ": " + event);
        }

        // Decorate event as an ApplicationEvent if necessary
        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...
        if (this.parent != null) {
            if (this.parent instanceof AbstractApplicationContext) {
                ((AbstractApplicationContext) this.parent).publishEvent(event, eventType);
            }
            else {
                this.parent.publishEvent(event);
            }
        }
    }

   

  总结:从Spring IoC的源码解析过程中,我们更加深入的了解容器的初始化,Bean的后置处理器,国际化,事件多播器发布事件,Bean的创建,属性的赋值,三级缓存解决循环依赖问题,Lifecycle的作用,spring系列完整代码在码云spring系列


推荐阅读
  • 深入解析SpringMVC核心组件:DispatcherServlet的工作原理
    本文详细探讨了SpringMVC的核心组件——DispatcherServlet的运作机制,旨在帮助有一定Java和Spring基础的开发人员理解HTTP请求是如何被映射到Controller并执行的。文章将解答以下问题:1. HTTP请求如何映射到Controller;2. Controller是如何被执行的。 ... [详细]
  • 采用IKE方式建立IPsec安全隧道
    一、【组网和实验环境】按如上的接口ip先作配置,再作ipsec的相关配置,配置文本见文章最后本文实验采用的交换机是H3C模拟器,下载地址如 ... [详细]
  • Kubernetes 持久化存储与数据卷详解
    本文深入探讨 Kubernetes 中持久化存储的使用场景、PV/PVC/StorageClass 的基本操作及其实现原理,旨在帮助读者理解如何高效管理容器化应用的数据持久化需求。 ... [详细]
  • 深入解析Java枚举及其高级特性
    本文详细介绍了Java枚举的概念、语法、使用规则和应用场景,并探讨了其在实际编程中的高级应用。所有相关内容已收录于GitHub仓库[JavaLearningmanual](https://github.com/Ziphtracks/JavaLearningmanual),欢迎Star并持续关注。 ... [详细]
  • 实用正则表达式有哪些
    小编给大家分享一下实用正则表达式有哪些,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下 ... [详细]
  • 配置多VLAN环境下的透明SQUID代理
    本文介绍如何在包含多个VLAN的网络环境中配置SQUID作为透明网关。网络拓扑包括Cisco 3750交换机、PANABIT防火墙和SQUID服务器,所有设备均部署在ESXi虚拟化平台上。 ... [详细]
  • 本文详细介绍了如何通过RPM包在Linux系统(如CentOS)上安装MySQL 5.6。涵盖了检查现有安装、下载和安装RPM包、配置MySQL以及设置远程访问和开机自启动等步骤。 ... [详细]
  • 深入理解Lucene搜索机制
    本文旨在帮助读者全面掌握Lucene搜索的编写步骤、核心API及其应用。通过详细解析Lucene的基本查询和查询解析器的使用方法,结合架构图和代码示例,带领读者深入了解Lucene搜索的工作流程。 ... [详细]
  • 深入解析for与foreach遍历集合时的性能差异
    本文将详细探讨for循环和foreach(迭代器)在遍历集合时的性能差异,并通过实际代码示例和源码分析,帮助读者理解这两种遍历方式的不同之处。文章内容丰富且专业,旨在为编程爱好者提供有价值的参考。 ... [详细]
  • 异常要理解Java异常处理是如何工作的,需要掌握一下三种异常类型:检查性异常:最具代表性的检查性异常是用户错误或问题引起的异常ÿ ... [详细]
  • 本文详细解析了Java中hashCode()和equals()方法的实现原理及其在哈希表结构中的应用,探讨了两者之间的关系及其实现时需要注意的问题。 ... [详细]
  • 中科院学位论文排版指南
    随着毕业季的到来,许多即将毕业的学生开始撰写学位论文。本文介绍了使用LaTeX排版学位论文的方法,特别是针对中国科学院大学研究生学位论文撰写规范指导意见的最新要求。LaTeX以其精确的控制和美观的排版效果成为许多学者的首选。 ... [详细]
  • Spring Boot单元测试中Redis连接失败的解决方案
    本文探讨了在Spring Boot项目中进行单元测试时遇到Redis连接问题的原因及解决方法,详细分析了配置文件加载路径不当导致的问题,并提供了有效的解决方案。 ... [详细]
  • Java 实现二维极点算法
    本文介绍了一种使用 Java 编程语言实现的二维极点算法。该算法用于从一组二维坐标中筛选出极点,适用于需要处理几何图形和空间数据的应用场景。文章不仅详细解释了算法的工作原理,还提供了完整的代码示例。 ... [详细]
  • 本题来自WC2014,题目编号为BZOJ3435、洛谷P3920和UOJ55。该问题描述了一棵不断生长的带权树及其节点上小精灵之间的友谊关系,要求实时计算每次新增节点后树上所有可能的朋友对数。 ... [详细]
author-avatar
米饭2502912051
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有