Spring容器的refresh()创建容器

//下面每一个方法都会单独提出来进行分析
@Override
public void refresh() throws BeansException, IllegalStateException {
    synchronized (this.startupShutdownMonitor) {
        // 刷新前的预处理
        prepareRefresh();
        // 获取 Bean工厂,默认的 DefaultListableBeanFactory
        ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
        // 准备bean工厂以供在此上下文中使用(对刚创建的bean工厂进行设置)
        prepareBeanFactory(beanFactory);
    try {
        // 允许在子类中对bean工厂进行后处理。目前是一个空实现
        //beanFactory 准备工作完成后进行的后置处理工作。
        postProcessBeanFactory(beanFactory);
        // 调用 BeanFactoryPostProcessors,
        //BeanFactoryPostProcessor:在 beanFactory 标准初始化完成之后执行的
        //两个接口 BeanFactoryPostProcessor、BeanDefinitionRegistryPostProcessor
        invokeBeanFactoryPostProcessors(beanFactory);
        // 注册bean的处理器,拦截bean的创建过程
        registerBeanPostProcessors(beanFactory);
        // 初始化messagesource 组件,做国际化功能、消息绑定、消息解析.
        initMessageSource();
        // 初始化事件派发器
        initApplicationEventMulticaster();
        // 初始化特定子类中的其他特殊bean。留给子容器(子类)是一个空的实现
        // 子类重写这个方法,在容器刷新的时候可以自定义逻辑
        onRefresh();
        // 将容器中将所有项目里面的 applicationLister 注册进来
        registerListeners();
        // 初始化所有剩下的单实例bean singletons.
        finishBeanFactoryInitialization(beanFactory);
        // 最后一步:刷新Bean工厂容器。
        finishRefresh();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

【1】prepareRefresh刷新前的预处理源码分析:

protected void prepareRefresh() {
    // 记录当前时间和容器的状态
    this.startupDate = System.currentTimeMillis();
    this.closed.set(false);
    this.active.set(true);
    // 在上下文环境中初始化属性设置,其底层是个空方法,由具体的子类定义其实现。
    initPropertySources();
    // 验证属性的合法性
    getEnvironment().validateRequiredProperties();
    //保存一些早期的容器事件
    this.earlyApplicationEvents = new LinkedHashSet<ApplicationEvent>();
}
1
2
3
4
5
6
7
8
9
10
11
12

【2】obtainFreshBeanFactory获取Bean工厂源码分析

protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
    //创建 beanFactory
    refreshBeanFactory();
    //获取 beanFactory
    return getBeanFactory();
}

//refreshBeanFactory 源码展示,位于GenericApplicationContext类
//创建 GenericApplicationContext 类的时候,默认会创建一个 bean 工厂。
public GenericApplicationContext() {
    this.beanFactory = new DefaultListableBeanFactory();
}
@Override
protected final void refreshBeanFactory() throws IllegalStateException {
    if (!this.refreshed.compareAndSet(false, true)) {
        throw new IllegalStateException(
                "GenericApplicationContext ... once");
    }
    //*** 给 bean工厂中创建一个序列化ID
    this.beanFactory.setSerializationId(getId());
}

//获取一个 bean 工厂
@Override
public final ConfigurableListableBeanFactory getBeanFactory() {
    return this.beanFactory;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

【3】prepareBeanFactory对刚创建的bean工厂进行设置,源码分析:

protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
    // 告诉内部bean工厂使用上下文的类加载器等。
    beanFactory.setBeanClassLoader(getClassLoader());
    //设置表达式解析器等
    beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
    beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

    // 添加部分后置处理器 ApplicationContextAwareProcessor
    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);

    // BeanFactory接口未在普通工厂中注册可解析类型
    // 注册可以解析的自动装配,我们能直接在任何组件中自动注入
    beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
    beanFactory.registerResolvableDependency(ResourceLoader.class, this);
    beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
    beanFactory.registerResolvableDependency(ApplicationContext.class, this);

    // 注册早期的后处理器,以便将内部bean检测为applicationlisteners。
    beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));

    // 添加编译时的 AspectJ
    if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
        beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
        // 为类型匹配设置临时类加载器。
        beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
    }

    // 给 beanfactory 中注册能用的一些组件。
    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());
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45

【4】invokeBeanFactoryPostProcessors源码分析

protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
    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()));
    }
}
1
2
3
4
5
6
7
8
9
10

【4.1】invokeBeanFactoryPostProcessors源码分析

public static void invokeBeanFactoryPostProcessors(
        ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {

    // 如果有,请先调用BeanDefinitionRegistryPostProcessors。
    Set<String> processedBeans = new HashSet<>();
        //当前的 beanFactory == BeanDefinitionRegistry
    if (beanFactory instanceof BeanDefinitionRegistry) {
        BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
        List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
        List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
                //获取所有的 BeanFactoryPostProcessor
        for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
            if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
                BeanDefinitionRegistryPostProcessor registryProcessor =
                        (BeanDefinitionRegistryPostProcessor) postProcessor;
                registryProcessor.postProcessBeanDefinitionRegistry(registry);
                registryProcessors.add(registryProcessor);
            }
            else {
                regularPostProcessors.add(postProcessor);
            }
        }

        // 首先执行实现了 priority 接口的后置处理器
        String[] postProcessorNames =
                beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
        for (String ppName : postProcessorNames) {
            if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
                currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                processedBeans.add(ppName);
            }
        }
        //限制性实现了 priorityOrdered 优先级接口的后置处理器
        sortPostProcessors(currentRegistryProcessors, beanFactory);
        registryProcessors.addAll(currentRegistryProcessors);
        invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
        currentRegistryProcessors.clear();

        // 接下来,调用实现ordered接口的后置处理器
        postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
        for (String ppName : postProcessorNames) {
            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);
        invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
        currentRegistryProcessors.clear();

        // 最后,调用所有其他没有实现任何接口的后置处理器
        boolean reiterate = true;
        while (reiterate) {
            reiterate = false;
            postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
            for (String ppName : postProcessorNames) {
                if (!processedBeans.contains(ppName)) {
                    currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                    processedBeans.add(ppName);
                    reiterate = true;
                }
            }
            sortPostProcessors(currentRegistryProcessors, beanFactory);
            registryProcessors.addAll(currentRegistryProcessors);
            invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
            currentRegistryProcessors.clear();
        }

        // 现在,调用到目前为止处理的所有处理器的postprocessebeanfactory回调。
        invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
        invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
    }

    else {
        // 调用使用上下文实例注册的工厂处理器。
        invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
    }

    // 不要在这里初始化factorybeans:我们需要保留所有常规bean
    // 获取所有的的后置处理器
    //后续操作与前面相同,查看是否实现了priority、order接口和获取全部
    String[] postProcessorNames =
            beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

    // Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
    // Ordered, and the rest.
    List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
    List<String> orderedPostProcessorNames = new ArrayList<>();
    List<String> nonOrderedPostProcessorNames = new ArrayList<>();
    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);
        }
    }

    // First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
    sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
    invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

    // Next, invoke the BeanFactoryPostProcessors that implement Ordered.
    List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>();
    for (String postProcessorName : orderedPostProcessorNames) {
        orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
    }
    sortPostProcessors(orderedPostProcessors, beanFactory);
    invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

    // Finally, invoke all other BeanFactoryPostProcessors.
    List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
    for (String postProcessorName : nonOrderedPostProcessorNames) {
        nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
    }
    invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);

    // Clear cached merged bean definitions since the post-processors might have
    // modified the original metadata, e.g. replacing placeholders in values...
    beanFactory.clearMetadataCache();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128

【5】registerBeanPostProcessors源码展示:注册BeanPostProcessor,不同的接口类型的BeanPostProcessor;在bean创建前后的执行时机是不一样的。
 ■  BeanPostProcessor:
 ■  DestructionAwareBeanPostProcessor
 ■  InstantiationAwareBeanPostProcessor
 ■  SmartInstantiationAwareBeanPostProcessor
 ■  MergedBeanDefinitionPostProcessor【internalPostProcessors】:优先记录:1

protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
    //方法实现在外层
    PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
}

public static void registerBeanPostProcessors(
        ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
    //获取所有的 bean后置处理器
    String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);

    // 检查和统计后置处理器
    int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
    beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

    // bean 的后置处理器也有实现 priority和order接口的后置处理器,用来指定优先级
    List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
    List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
    List<String> orderedPostProcessorNames = new ArrayList<>();
    List<String> nonOrderedPostProcessorNames = new ArrayList<>();
    for (String ppName : postProcessorNames) {
        if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
            BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
            priorityOrderedPostProcessors.add(pp);
            //将实现了 MergedBeanDefinitionPostProcessor 接口的后置处理器加入到internalPostProcessors
            if (pp instanceof MergedBeanDefinitionPostProcessor) {
                internalPostProcessors.add(pp);
            }
        }
        else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
            orderedPostProcessorNames.add(ppName);
        }
        else {
            nonOrderedPostProcessorNames.add(ppName);
        }
    }

    // 首先,注册实现priorityordered接口的beanPostProcessors。
    sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
    //注册bean后置处理器到beanFactory
    //beanFactory.addBeanPostProcessor(postProcessor);
    registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

    // 接下来,注册实现ordered接口的beanPostProcessors。
    List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>();
    for (String ppName : orderedPostProcessorNames) {
        BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
        orderedPostProcessors.add(pp);
        if (pp instanceof MergedBeanDefinitionPostProcessor) {
            internalPostProcessors.add(pp);
        }
    }
    sortPostProcessors(orderedPostProcessors, beanFactory);
    registerBeanPostProcessors(beanFactory, orderedPostProcessors);

    // 现在,注册所有常规beanpstprocessors。
    List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
    for (String ppName : nonOrderedPostProcessorNames) {
        BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
        nonOrderedPostProcessors.add(pp);
        if (pp instanceof MergedBeanDefinitionPostProcessor) {
            internalPostProcessors.add(pp);
        }
    }
    registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);

    // 最后,重新注册所有内部 beanpstprocessors。实现了 MergedBeanDefinitionPostProcessor 接口的后置处理器
    sortPostProcessors(internalPostProcessors, beanFactory);
    registerBeanPostProcessors(beanFactory, internalPostProcessors);

    // 注册一个ApplicationListenerDetector 来检查bean创建完成是否为侦听器,如果是将此bean 放入到容器中
    // 将其移动到处理器链的末端(用于获取代理等)。
    beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73

【6】initMessageSource源码解析:

protected void initMessageSource() {
    //获取 bean工厂
    ConfigurableListableBeanFactory beanFactory = getBeanFactory();
    //查看beanFactory 中是否有 messsource 类型组件,有则赋值给messageSource
    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());
            }
        }
        if (logger.isTraceEnabled()) {
            logger.trace("Using MessageSource [" + this.messageSource + "]");
        }
    }
    //不存在则创建一个 messageSource 主要作用:从配置文件中取出国际化等的值
    else {
        DelegatingMessageSource dms = new DelegatingMessageSource();
        dms.setParentMessageSource(getInternalParentMessageSource());
        this.messageSource = dms;
        //将messageSource 注入到容器中
        beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
        if (logger.isTraceEnabled()) {
            logger.trace("No '" + MESSAGE_SOURCE_BEAN_NAME + "' bean, using [" + this.messageSource + "]");
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

【7】initApplicationEventMulticaster初始化事件派发器,源码分析:

protected void initApplicationEventMulticaster() {
    //获取 BeanFactory
    ConfigurableListableBeanFactory beanFactory = getBeanFactory();
    //从beanFactory 中获取 applicationEventMulticaster 的事件派发器
    if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
        this.applicationEventMulticaster =
                beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
        if (logger.isTraceEnabled()) {
            logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
        }
    }
    //否则创建一个简单的事件派发器 SimpleApplicationEventMulticaster
    else {
        this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
        //并注册到容器中,以后其他组件直接注入。
        beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
        if (logger.isTraceEnabled()) {
            logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " +
                    "[" + this.applicationEventMulticaster.getClass().getSimpleName() + "]");
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

【8】registerListeners源码分析:

protected void registerListeners() {
    // 首先注册静态指定的侦听器。
    for (ApplicationListener<?> listener : getApplicationListeners()) {
        //将监听器添加到事件派发器中
        getApplicationEventMulticaster().addApplicationListener(listener);
    }

    // 从容器中获取所有的 ApplicationListener
    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);
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

【9】初始化所有剩下的单实例bean的方法finishBeanFactoryInitialization(beanFactory); 源码展示:

protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
    // 初始化上下文的转换服务。   (过)
    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));
    }

    // 如果没有bean后处理器,则注册默认的嵌入式值解析器   (过)
    // (例如propertyplaceholderconfigurer bean)在以下任何时间之前注册:
    // 此时,主要用于注释属性值中的分辨率。
    if (!beanFactory.hasEmbeddedValueResolver()) {
        beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
    }

    // 尽早初始化loadTimeWeaveraware bean,以便尽早注册其转换器。  (过)
    String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
    for (String weaverAwareName : weaverAwareNames) {
        getBean(weaverAwareName);
    }

    // 停止使用临时类加载器进行类型匹配。  (过)
    beanFactory.setTempClassLoader(null);

    // 允许缓存所有bean定义元数据,不需要进一步更改。  (过)
    beanFactory.freezeConfiguration();

    // *****实例化所有剩余的(非延迟初始化)单例。***
    beanFactory.preInstantiateSingletons();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

【9.1】实例化所有剩余的(非延迟初始化)单例。beanFactory.preInstantiateSingletons() 方法源码如下:

@Override
public void preInstantiateSingletons() throws BeansException {
    if (logger.isTraceEnabled()) {
        logger.trace("Pre-instantiating singletons in " + this);
    }

    // 获取所有bean的定义信息
    List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);

    // 所有非惰性单例bean的触发器初始化…
    for (String beanName : beanNames) {
        //获取bean的定义信息
        RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
        //判断不是抽象的、是单实例的、不是懒加载的则创建
        if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
            //判断是否为 Factorybean:是否是实现了factoryBean接口的,通过getObject 获取实例
            if (isFactoryBean(beanName)) {
                Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
                if (bean instanceof FactoryBean) {
                    final FactoryBean<?> factory = (FactoryBean<?>) bean;
                    boolean isEagerInit;
                    if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
                        isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>)
                                        ((SmartFactoryBean<?>) factory)::isEagerInit,
                                getAccessControlContext());
                    }
                    else {
                        isEagerInit = (factory instanceof SmartFactoryBean &&
                                ((SmartFactoryBean<?>) factory).isEagerInit());
                    }
                    if (isEagerInit) {
                        getBean(beanName);
                    }
                }
            }
            /**
             * 如果不是工厂bean——>getBean(beanName)---> doGetBean()--->获取缓存中保存的单实例Bean,如果能
             * singletonObjects.get(beanName); Map<String, Object> singletonObjects用来缓存所有的单实例bean
             * -->缓存中获取不到,则创建对象:
             * 1、先标记当前bean 被创建(防止多线程)
             * 2、获取bean的定义信息
             * 3、获取当前bean依赖的其他bean(dependsOn),如果有按照getBean的方式,将依赖的bean先创建出来
             * 4、启动单实例bean的创建流程:通过beanFactory.getObject创建——>内部调用createBean创建bean——>
             *拿到bean的定义信息,调用resolveBeforeInstantiation(beanName,mbdToUse):让beanPoseProcess提前
             *拦截获取代理对象的机会。InstantiationAwareBeanPostProcessor:提前执行,
             *先触发postProcessBeforeInstantiation();如果有返回值则触发postProcessAfterInitalization()
             *如果没有返回代理对象,则执行 doCreateBean(beanName,mbdToUse,args)创建bean。
             *创建bean的流程:
             * 1)、createBeanInstance(beanName,mbdToUse,args)进入此方法:
             *      1.1)通过工厂方法或者执行构造器解析执行即可:创建的对象是个空对象
             * 2)、applyMergedBeanDefinitionPostProcessors(mbd,beanType,beanName);调用
             *       MergedBeanDefinitionPostProcessor的bdp.postProcessMergedBeanDefinition(mbd,beanType,beanName)
             * 3)、给bean实例赋值,populateBean(beanName,mbd,bw,pvs) 获取所有的属性信息,赋值之前获取所有的 InstantiationAwareBeanPostProcessor 后置处理器的postProcessAfterInstantiation()
             * 第二次获取InstantiationAwareBeanPostProcessor后置处理器;执行 postProcessPropertyValues()
             * 最后为应用 Bean属性赋值:为属性利用 setter 方法进行赋值 applyPropertyValues(beanName,mbd,bw,pvs)
             * 4)、bean 初始化:initializeBean(beanName,bean,mbd)
             *   ①、执行xxxAware接口的方法,调用实现了BeanNameAware、BeanClassLoaderAware、BeanFactoryAware接口的方法。
             *   ②、执行后置处理器之前的方法:applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName)
             *      所有后置处理器的 BeanPostProcessor.postProcessBeforeInitialization()
             *   ③、执行初始化方法:invokeInitMethods(beanName, wrappedBean, mbd);
             *        先判断是否实现了InitializingBean接口的实现;执行接口规定的初始化。
             *      其次自定义初始化方法。
             *   ④、applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);执行初始化之后的后置处理器的方法。
             *       BeanPostProcessor.postProcessAfterInitialization(result, beanName);
             * 5)、注册bean的销毁方法到容器中registerDisposableBeanIfNecessary(beanName, bean, mbd);
             *
             * 5、将创建的bean 添加到缓存中singleObject(Map);其实IOC容器就是这些Map集合,很多Map里面保存了单实例Bean,环境信息等等。。。
             **/
            else {
                getBean(beanName);
            }
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74

【9.2】所有Bean都利用getBean创建完成之后,检查所有的Bean是否实现了SmartInitializingSingleton接口,如果是,就执行smartSingleton.afterSingletonsInstantiated();

for (String beanName : beanNames) {
    Object singletonInstance = getSingleton(beanName);
    if (singletonInstance instanceof SmartInitializingSingleton) {
        final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
        if (System.getSecurityManager() != null) {
            AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
                smartSingleton.afterSingletonsInstantiated();
                return null;
            }, getAccessControlContext());
        }
        else {
            smartSingleton.afterSingletonsInstantiated();
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

【10】finishRefresh:最后一步,完成BeanFactory的初始化创建工作;IOC容器创建完成。

用户可以实现LifecycleProcessor接口,可以在BeanFactory执行void onRefresh(); 和void onClose();时调用。默认从容器中找是否有 LifecycleProcessor的组件。如果没有则创建一个默认的声明周期组件:new DefaultLifecycleProcessor();并注册到beanFactory容器中。

protected void finishRefresh() {
    // 清除上下文级资源缓存(例如扫描中的asm元数据)。
    clearResourceCaches();
    // 初始化与生命周期有关的后置处理器
    initLifecycleProcessor();
    //获取前面定义的声明周期处理器(BeanFactory)并调用回调方法 onRefresh
    getLifecycleProcessor().onRefresh();
    // 发布容器刷新完成事件
    publishEvent(new ContextRefreshedEvent(this));

    // 不重要。。。
    LiveBeansView.registerApplicationContext(this);
}
1
2
3
4
5
6
7
8
9
10
11
12
13

# Spring IOC 容器源码总结

【1】Spring容器在启动的时候,先会保存所有注册来的Bean的定义信息;
 ■  Xml注册bean<bean>
 ■  注解注册Bean@Service@Component@Bean等等
【2】Spring容器会在合适的时机创建bean
 ■  用到这个bean的时候,利用getBean创建bean,创建好后保存在容器中。
 ■  统一创建剩下所有bean的时候,调用finishBeanFactoryInitialization()
【3】后置处理器:BeanPostProcessor:每一个bean的创建完成,都会使用各种后置处理器进行处理,来增强bean 的功能:
 ■  AutowriteAnnotationBeanPostProcessor:处理自动注入;
 ■  AnnotationAwareAspectJAutoProxyCreator:来做AOP 功能;等等。。。
【4】事件驱动模型:ApplicationListener 事件监听。ApplicationEventMulticaster 事件派发。

#

(adsbygoogle = window.adsbygoogle || []).push({});