一. refresh() 方法预览

Spring 容器启动时会创建IOC容器,在创建容器时,会调用 refresh()方法,整个容器就是通过该方法,完成所有的 bean 的创建以及初始化
在这里插入图片描述

二. refresh() 方法中调用的每个方法

1. this.prepareRefresh() 激活开启容器

	protected void prepareRefresh() {
		//记录时间
        this.startupDate = System.currentTimeMillis();
        //设置当前容器未关闭
        this.closed.set(false);
        //设置当前容器已激活
        this.active.set(true);
        if (this.logger.isInfoEnabled()) {
        	//打印容器刷新日志
            this.logger.info("Refreshing " + this);
        }
		//初始化一下属性(该方法默认是空的,是提供给子类来实现的,
		//假设我们有些工作需要在初始化bean以前就要加载设置等,可以通过重写这个方法来完成)
        this.initPropertySources();
        //校验设置的属性是否合法
        this.getEnvironment().validateRequiredProperties();
        //初始化一个集合属性,提供用来保存后面创建的事件,如果有事件发生会放入这个集合中
        this.earlyApplicationEvents = new LinkedHashSet();
    }

2. this.obtainFreshBeanFactory() 获取 bean 工厂

protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
		//刷新bean工厂,创建一个 DefaultListableBeanFactory类型的 bean工厂
		//赋值给 beanFactory 属性,对创建的这个 beanFactory 设置一个序列号
        this.refreshBeanFactory();
        //获取beanFactory,就上将上一步设置好序列号的的beanFactory返回回来
        ConfigurableListableBeanFactory beanFactory = this.getBeanFactory();
        //打印日志
        if (this.logger.isDebugEnabled()) {
            this.logger.debug("Bean factory for " + this.getDisplayName() + ": " + beanFactory);
        }
		//将创建好的 beanFactory 返回
        return beanFactory;
    }

3. this.prepareBeanFactory(beanFactory) 对获取到的 beanFactory 做预处理设置

就是上一步获取到的beanFactory是一个创建出来什么都没有的空工厂,此处进行设置

protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
		//设置类加载器
        beanFactory.setBeanClassLoader(this.getClassLoader());
        //设置表达式语言解析器....
        beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
        beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, this.getEnvironment()));
        //设置添加一个 tApplicationContextAwareProcessor 后置处理器
        beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
        
        //设置忽略的自动装配的接口,就是设置这些接口的实现类不能通过这些接口实现自动注入
        beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
        beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
        beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
        beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
        beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
        beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
		
		//注册可以解析的自动装配,假设想要使用@Autowired 注解将Spring提供的 BeanFactory 
		//装配到自己,创建的某个类的属性上,就要在此处设置
        beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
        beanFactory.registerResolvableDependency(ResourceLoader.class, this);
        beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
        beanFactory.registerResolvableDependency(ApplicationContext.class, this);

		//设置添加一个ApplicationListenerDetector后置处理器
        beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
		
		//添加编译时支持AspectJ
        if (beanFactory.containsBean("loadTimeWeaver")) {
            beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
            beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
        }

		//向beanFactory中注册组件
        if (!beanFactory.containsLocalBean("environment")) {
        	//注册了一个 Environment,该对象中存了一下我们默认的属性
            beanFactory.registerSingleton("environment", this.getEnvironment());
        }

        if (!beanFactory.containsLocalBean("systemProperties")) {
        	//向beanFactory中注册了系统属性属性(一个Map集合)
            beanFactory.registerSingleton("systemProperties", this.getEnvironment().getSystemProperties());
        }

        if (!beanFactory.containsLocalBean("systemEnvironment")) {
        	//向beanFactory中注册环境变量等相关信息(一个Map集合)
            beanFactory.registerSingleton("systemEnvironment", this.getEnvironment().getSystemEnvironment());
        }
    }

4. this.postProcessBeanFactory(beanFactory); beanFactory准备工作完成后进行的后置处理工作

该方法默认是空的,为子类通过的,假设后续开发中,在 beanFactory 创建并且有准备完成后需要执行某些操作,可以提供子类重写这个方法来实现
以上可以看为beanFactory 的创建及预准备工作==========================================

5. this.invokeBeanFactoryPostProcessors(beanFactory) 执行 beanFactory 后置处理器的方法

执行实现了 BeanFactoryPostProcessors 接口的beanFactory后置处理器中方法,也就是beanFactory初始化完成后要执行的方法
注意 beanFactory 后置处理器 BeanFactoryPostProcessor 与 BeanDefinitionRegistryPostProcessor的不同

protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
		//执行beanFactory后置处理器中的方法,该方法中获取所有BeanFactoryPostProcessor,遍历判断
		//对不同的BeanFactoryPostProcessor进行排序,因为先后执行的顺序不同,
		//PriorityOrdered>BeanDefinitionRegistryPostProcessor>BeanFactoryPostProcessor
		//然后执行后置处理器中定义的初始化 beanFactory 后要执行的方法
        PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, this.getBeanFactoryPostProcessors());
        if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean("loadTimeWeaver")) {
            beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
            beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
        }
    }
public static void invokeBeanFactoryPostProcessors(
        ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {

    // Invoke BeanDefinitionRegistryPostProcessors first, if any.
    Set<String> processedBeans = new HashSet<String>();
 
    // 1.判断beanFactory是否为BeanDefinitionRegistry,beanFactory为DefaultListableBeanFactory,
    // 而DefaultListableBeanFactory实现了BeanDefinitionRegistry接口,因此这边为true
    if (beanFactory instanceof BeanDefinitionRegistry) {
        BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
        // 用于存放普通的BeanFactoryPostProcessor
        List<BeanFactoryPostProcessor> regularPostProcessors = new LinkedList<BeanFactoryPostProcessor>();
        // 用于存放BeanDefinitionRegistryPostProcessor
        List<BeanDefinitionRegistryPostProcessor> registryProcessors = new LinkedList<BeanDefinitionRegistryPostProcessor>();
 
        // 2.首先处理入参中的beanFactoryPostProcessors
        // 遍历所有的beanFactoryPostProcessors, 将BeanDefinitionRegistryPostProcessor和普通BeanFactoryPostProcessor区分开
        for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
            if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
                // 2.1 如果是BeanDefinitionRegistryPostProcessor
                BeanDefinitionRegistryPostProcessor registryProcessor =
                        (BeanDefinitionRegistryPostProcessor) postProcessor;
                // 2.1.1 直接执行BeanDefinitionRegistryPostProcessor接口的postProcessBeanDefinitionRegistry方法
                registryProcessor.postProcessBeanDefinitionRegistry(registry);
                // 2.1.2 添加到registryProcessors(用于最后执行postProcessBeanFactory方法)
                registryProcessors.add(registryProcessor);
            } else {
                // 2.2 否则,只是普通的BeanFactoryPostProcessor
                // 2.2.1 添加到regularPostProcessors(用于最后执行postProcessBeanFactory方法)
                regularPostProcessors.add(postProcessor);
            }
        }
 
        // Do not initialize FactoryBeans here: We need to leave all regular beans
        // uninitialized to let the bean factory post-processors apply to them!
        // Separate between BeanDefinitionRegistryPostProcessors that implement
        // PriorityOrdered, Ordered, and the rest.
        // 用于保存本次要执行的BeanDefinitionRegistryPostProcessor
        List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<BeanDefinitionRegistryPostProcessor>();
 
        // 3.调用所有实现PriorityOrdered接口的BeanDefinitionRegistryPostProcessor实现类
        // 3.1 找出所有实现BeanDefinitionRegistryPostProcessor接口的Bean的beanName
        String[] postProcessorNames =
                beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
        // 3.2 遍历postProcessorNames
        for (String ppName : postProcessorNames) {
            // 3.3 校验是否实现了PriorityOrdered接口
            if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
                // 3.4 获取ppName对应的bean实例, 添加到currentRegistryProcessors中,
                // beanFactory.getBean: 这边getBean方法会触发创建ppName对应的bean对象, 目前暂不深入解析
                currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                // 3.5 将要被执行的加入processedBeans,避免后续重复执行
                processedBeans.add(ppName);
            }
        }
        // 3.6 进行排序(根据是否实现PriorityOrdered、Ordered接口和order值来排序)
        sortPostProcessors(currentRegistryProcessors, beanFactory);
        // 3.7 添加到registryProcessors(用于最后执行postProcessBeanFactory方法)
        registryProcessors.addAll(currentRegistryProcessors);
        // 3.8 遍历currentRegistryProcessors, 执行postProcessBeanDefinitionRegistry方法
        invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
        // 3.9 执行完毕后, 清空currentRegistryProcessors
        currentRegistryProcessors.clear();
 
        // Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
        // 4.调用所有实现了Ordered接口的BeanDefinitionRegistryPostProcessor实现类(过程跟上面的步骤3基本一样)
        // 4.1 找出所有实现BeanDefinitionRegistryPostProcessor接口的类, 这边重复查找是因为执行完上面的BeanDefinitionRegistryPostProcessor,
        // 可能会新增了其他的BeanDefinitionRegistryPostProcessor, 因此需要重新查找
        postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
        for (String ppName : postProcessorNames) {
            // 校验是否实现了Ordered接口,并且还未执行过
            if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
                currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                processedBeans.add(ppName);
            }
        }
        sortPostProcessors(currentRegistryProcessors, beanFactory);
        registryProcessors.addAll(currentRegistryProcessors);
        // 4.2 遍历currentRegistryProcessors, 执行postProcessBeanDefinitionRegistry方法
        invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
        currentRegistryProcessors.clear();
 
        // Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
        // 5.最后, 调用所有剩下的BeanDefinitionRegistryPostProcessors
        boolean reiterate = true;
        while (reiterate) {
            reiterate = false;
            // 5.1 找出所有实现BeanDefinitionRegistryPostProcessor接口的类
            postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
            for (String ppName : postProcessorNames) {
                // 5.2 跳过已经执行过的
                if (!processedBeans.contains(ppName)) {
                    currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                    processedBeans.add(ppName);
                    // 5.3 如果有BeanDefinitionRegistryPostProcessor被执行, 则有可能会产生新的BeanDefinitionRegistryPostProcessor,
                    // 因此这边将reiterate赋值为true, 代表需要再循环查找一次
                    reiterate = true;
                }
            }
            sortPostProcessors(currentRegistryProcessors, beanFactory);
            registryProcessors.addAll(currentRegistryProcessors);
            // 5.4 遍历currentRegistryProcessors, 执行postProcessBeanDefinitionRegistry方法
            invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
            currentRegistryProcessors.clear();
        }
 
        // 6.调用所有BeanDefinitionRegistryPostProcessor的postProcessBeanFactory方法(BeanDefinitionRegistryPostProcessor继承自BeanFactoryPostProcessor)
        invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
        // 7.最后, 调用入参beanFactoryPostProcessors中的普通BeanFactoryPostProcessor的postProcessBeanFactory方法
        invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
    } else {
        // Invoke factory processors registered with the context instance.
        invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
    }
 
    // 到这里 , 入参beanFactoryPostProcessors和容器中的所有BeanDefinitionRegistryPostProcessor已经全部处理完毕,
    // 下面开始处理容器中的所有BeanFactoryPostProcessor
 
    // 8.找出所有实现BeanFactoryPostProcessor接口的类
    String[] postProcessorNames =
            beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
 
    // 用于存放实现了PriorityOrdered接口的BeanFactoryPostProcessor
    List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
    // 用于存放实现了Ordered接口的BeanFactoryPostProcessor的beanName
    List<String> orderedPostProcessorNames = new ArrayList<String>();
    // 用于存放普通BeanFactoryPostProcessor的beanName
    List<String> nonOrderedPostProcessorNames = new ArrayList<String>();
    // 8.1 遍历postProcessorNames, 将BeanFactoryPostProcessor按实现PriorityOrdered、实现Ordered接口、普通三种区分开
    for (String ppName : postProcessorNames) {
        // 8.2 跳过已经执行过的
        if (processedBeans.contains(ppName)) {
            // skip - already processed in first phase above
        } else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
            // 8.3 添加实现了PriorityOrdered接口的BeanFactoryPostProcessor
            priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
        } else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
            // 8.4 添加实现了Ordered接口的BeanFactoryPostProcessor的beanName
            orderedPostProcessorNames.add(ppName);
        } else {
            // 8.5 添加剩下的普通BeanFactoryPostProcessor的beanName
            nonOrderedPostProcessorNames.add(ppName);
        }
    }
 
    // 9.调用所有实现PriorityOrdered接口的BeanFactoryPostProcessor
    // 9.1 对priorityOrderedPostProcessors排序
    sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
    // 9.2 遍历priorityOrderedPostProcessors, 执行postProcessBeanFactory方法
    invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
 
    // 10.调用所有实现Ordered接口的BeanFactoryPostProcessor
    List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
    for (String postProcessorName : orderedPostProcessorNames) {
        // 10.1 获取postProcessorName对应的bean实例, 添加到orderedPostProcessors, 准备执行
        orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
    }
    // 10.2 对orderedPostProcessors排序
    sortPostProcessors(orderedPostProcessors, beanFactory);
    // 10.3 遍历orderedPostProcessors, 执行postProcessBeanFactory方法
    invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
 
    // 11.调用所有剩下的BeanFactoryPostProcessor
    List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
    for (String postProcessorName : nonOrderedPostProcessorNames) {
        // 11.1 获取postProcessorName对应的bean实例, 添加到nonOrderedPostProcessors, 准备执行
        nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
    }
    // 11.2 遍历nonOrderedPostProcessors, 执行postProcessBeanFactory方法
    invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);

    // 12.清除元数据缓存(mergedBeanDefinitions、allBeanNamesByType、singletonBeanNamesByType),
    // 因为后处理器可能已经修改了原始元数据,例如, 替换值中的占位符...
    beanFactory.clearMetadataCache();
}

6. this.registerBeanPostProcessors(beanFactory) 注册 bean 的后置处理器

注意不同的 BeanPostProcessors,该接口下的子接口: 不同接口的执行时机不同
DestructionAwareBeanPostProcessor
InstantiationAwareBeanProcessor
SmartInstantiationAwareBeanPostProcessor
MergedBeanDefinitionPostProcessor

public static void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
		//根据类型获取 beanFactory 中所有的 BeanPostProcessor 名字
        String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
        int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
        //添加了一个后置处理器,通过添加的这个后置处理器检查 前获取的这些后置处理器 BeanPostProcessorChecker 是一个内部类,继承了BeanPostProcessor接口
        beanFactory.addBeanPostProcessor(new PostProcessorRegistrationDelegate.BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
        //创建两个集合用来存放不同的BeanPostProcessor,通过这两个集合对不同的BeanPostProcessor 进行排序
        List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList();
        List<BeanPostProcessor> internalPostProcessors = new ArrayList();
        List<String> orderedPostProcessorNames = new ArrayList();
        List<String> nonOrderedPostProcessorNames = new ArrayList();
        String[] var8 = postProcessorNames;
        int var9 = postProcessorNames.length;

        String ppName;
        BeanPostProcessor pp;
       	//遍历获取 BeanPostProcessor, 判断不同的 BeanPostProcessor 放入不同的集合中
		//实现了 PriorityOrdered 的放入priorityOrderedPostProcessors集合中
		//实现了PriorityOrdered 并且是MergedBeanDefinitionPostProcessor类型的放入internalPostProcessors
		//实现了 Ordered 的放入 orderedPostProcessorNames 集合中
		//否则放入 nonOrderedPostProcessorNames 集合中
        for(int var10 = 0; var10 < var9; ++var10) {
            ppName = var8[var10];
            if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
                pp = (BeanPostProcessor)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);
            }
        }
		//首先对 priorityOrderedPostProcessors 中的进行排序
        sortPostProcessors(beanFactory, priorityOrderedPostProcessors);
        //注册,也就是创建BeanPostProcessor设置到beanFactory中
        registerBeanPostProcessors(beanFactory, (List)priorityOrderedPostProcessors);
        List<BeanPostProcessor> orderedPostProcessors = new ArrayList();
        Iterator var14 = orderedPostProcessorNames.iterator();

		//遍历orderedPostProcessorNames集合中的BeanPostProcessor 如果有
		//MergedBeanDefinitionPostProcessor类型的,将这个类型的后置处理器放入internalPostProcessors集合
        while(var14.hasNext()) {
            String ppName = (String)var14.next();
            BeanPostProcessor pp = (BeanPostProcessor)beanFactory.getBean(ppName, BeanPostProcessor.class);
            orderedPostProcessors.add(pp);
            if (pp instanceof MergedBeanDefinitionPostProcessor) {
                internalPostProcessors.add(pp);
            }
        }
		//对orderedPostProcessors集合中的后置处理器排序
        sortPostProcessors(beanFactory, orderedPostProcessors);
        //注册
        registerBeanPostProcessors(beanFactory, (List)orderedPostProcessors);
        List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList();
        Iterator var17 = nonOrderedPostProcessorNames.iterator();
		//继续排序,分类
        while(var17.hasNext()) {
            ppName = (String)var17.next();
            pp = (BeanPostProcessor)beanFactory.getBean(ppName, BeanPostProcessor.class);
            nonOrderedPostProcessors.add(pp);
            if (pp instanceof MergedBeanDefinitionPostProcessor) {
                internalPostProcessors.add(pp);
            }
        }
		//注册nonOrderedPostProcessors集合中的后置处理器
        registerBeanPostProcessors(beanFactory, (List)nonOrderedPostProcessors);
        //对internalPostProcessors集合中的后置处理器进行排序
        sortPostProcessors(beanFactory, internalPostProcessors);
        //注册internalPostProcessors集合中的后置处理器
        registerBeanPostProcessors(beanFactory, (List)internalPostProcessors);
        
        //又添加了一个后置处理器ApplicationListenerDetector,
		//该后置处理器用来判断是否是某个监听器,如果是添加到容器中
        beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
    }

7. this.initMessageSource() 初始化 MessageSource 组件

在 SpringMVC 中用来做国际化功能,消息解析,消息绑定,MessageSource中有getMessage()方法,一般用来取出国际化配置文件中的key的值,能按照区域信息去获取

protected void initMessageSource() {
		//获取beanFactory
        ConfigurableListableBeanFactory beanFactory = this.getBeanFactory();
        //判断beanFactory中是否有一个id为"messageSource" 的 bean
        if (beanFactory.containsLocalBean("messageSource")) {
        	//如果有通过id获取这个bean,赋值给 messageSource  属性
            this.messageSource = (MessageSource)beanFactory.getBean("messageSource", MessageSource.class);
            if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
                HierarchicalMessageSource hms = (HierarchicalMessageSource)this.messageSource;
                if (hms.getParentMessageSource() == null) {
                    hms.setParentMessageSource(this.getInternalParentMessageSource());
                }
            }

            if (this.logger.isDebugEnabled()) {
                this.logger.debug("Using MessageSource [" + this.messageSource + "]");
            }
        } else {
        	//如果没有创建一个MessageSource组件
            DelegatingMessageSource dms = new DelegatingMessageSource();
            //将这个组件注册到容器中(以后获取国际化配置文件的相关信息,可以通过@Autowired在Spring
            //容器中直接获取装配到自己的类的属性上,然后调用MessageSource的方法)
            dms.setParentMessageSource(this.getInternalParentMessageSource());
            this.messageSource = dms;
            beanFactory.registerSingleton("messageSource", this.messageSource);
            if (this.logger.isDebugEnabled()) {
                this.logger.debug("Unable to locate MessageSource with name 'messageSource': using default [" + this.messageSource + "]");
            }
        }

    }

8. this.initApplicationEventMulticaster() 初始化事件派发器,多播器

protected void initApplicationEventMulticaster() {
		//获取beanFactory
        ConfigurableListableBeanFactory beanFactory = this.getBeanFactory();
        //1.获取beanFactory中id为"applicationEventMulticaster"的事件派发器
        if (beanFactory.containsLocalBean("applicationEventMulticaster")) {
            this.applicationEventMulticaster = (ApplicationEventMulticaster)beanFactory.getBean("applicationEventMulticaster", ApplicationEventMulticaster.class);
            if (this.logger.isDebugEnabled()) {
                this.logger.debug("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
            }
        } else {
        	//如果没有创建一个 SimpleApplicationEventMulticaster 事件派发器,
            this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
            //注册到 Spring 容器中
            beanFactory.registerSingleton("applicationEventMulticaster", this.applicationEventMulticaster);
            if (this.logger.isDebugEnabled()) {
                this.logger.debug("Unable to locate ApplicationEventMulticaster with name 'applicationEventMulticaster': using default [" + this.applicationEventMulticaster + "]");
            }
        }

    }

9. this.onRefresh() 用来初始化子容器中的bean,默认是空方法

可以提供子类重写这个方法,在容器刷新时,做些其它操作

10. this.registerListeners() 注册监听器

protected void registerListeners() {
        Iterator var1 = this.getApplicationListeners().iterator();

        while(var1.hasNext()) {
            ApplicationListener<?> listener = (ApplicationListener)var1.next();
            this.getApplicationEventMulticaster().addApplicationListener(listener);
        }
		//在容器中拿到所有的监听器的名字
        String[] listenerBeanNames = this.getBeanNamesForType(ApplicationListener.class, true, false);
        String[] var7 = listenerBeanNames;
        int var3 = listenerBeanNames.length;
		
		//遍历,将每个监听器添加到事件派发器中
        for(int var4 = 0; var4 < var3; ++var4) {
            String listenerBeanName = var7[var4];
            this.getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
        }

		//获取早期设置的事件(派发之前的事件)
        Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
        this.earlyApplicationEvents = null;
        //如果有
        if (earlyEventsToProcess != null) {
            Iterator var9 = earlyEventsToProcess.iterator();

            while(var9.hasNext()) {
                ApplicationEvent earlyEvent = (ApplicationEvent)var9.next();
                //将早期的事件派发出去
                this.getApplicationEventMulticaster().multicastEvent(earlyEvent);
            }
        }
    }

11. this.finishBeanFactoryInitialization(beanFactory) 初始化所有剩下的单实例 bean

具体查看 Spring Bean 初始化与销毁通

12. this.finishRefresh() 完成ben的创建初始化工作,完成 IOC 容器的创建

protected void finishRefresh() {
		//初始化跟生命周期有关的后置处理器,在容器中获取LifecycleProcessor
		//类型的后置处理器接口,在容器刷新完成以及关闭时执行的方法,此处是注册
		//如果没有会注册一个默认的生命周期组件
        this.initLifecycleProcessor();
        //拿到生命周期处理器,回调onRefresh()容器刷新完成方法,
        this.getLifecycleProcessor().onRefresh();
        //发布容器刷新完成事件
        this.publishEvent((ApplicationEvent)(new ContextRefreshedEvent(this)));
        LiveBeansView.registerApplicationContext(this);
    }

三. 总结

  1. Spring 启动容器时,首先开启激活容器,
  2. 创建初始化 beanFactory ,扫描保存所有注入的bean的定义信息
  3. Spring 创建bean 首先创建实现了 BeanPostProcessors 接口的后置处理器,创建组件相关的bean,例如,国际化的MessageSource 组件, EventMulticaster事件派发器,Listeners 注册监听器等
  4. 然后创建其他剩下的单实例bean,在其它单实例bean被创建时,会被后置处理器监控到,执行创建前后,或初始化前后,定义在后置处理器中的方法: 例如
    • AutowiredAnnotationBeanPostProcessor : 通过该后置处理器完成注解自动注入的功能
    • AnnotationAwareAspectJAutoProxyCreator: 通过该后置处理器设置AOP时,对指定目标方法所在类生成动态代理类
    • AsyncAnnotationBeanPostProcessor : 设置异步的后置处理器
    • 还有设置定时任务的…
Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐