Spring IOC 源码分析


什么是 IoC

IoC (Inversion of control )控制反转。它是一种思想不是一个技术实现。描述的是:java开发领域对象的创建以及管理的问题。

例如:现有类A依赖于类B。传统的开发方式 :往往是在类A中手动通过new关键字来new一个B的对象出来使用IoC思想的开发方式 :不通过new关键字来创建对象,而是通过IoC容器(Spring框架) 来帮助我们实例化对象。我们需要哪个对象,直接从IoC 容器里面过去即可。
从以上两种开发方式的对比来看:我们 “丧失了一个权力” (创建、管理对象的权力),从而也得到了一个好处(不用再考虑对象的创建、管理等一系列的事情)

IoC容器主要有两个容器系列BeanFactoryApplicationContext

IoC容器主要的接口设计图:

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】prepareRefresh刷新前的预处理源码分析:

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

【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;
}

【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());
    }
}

【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()));
    }
}

【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();
}

【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));
}

【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 + "]");
        }
    }
}

【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() + "]");
        }
    }
}

【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);
        }
    }
}

【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();
}

【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);
            }
        }
    }
}

【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();
        }
    }
}

【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);
}

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事件派发。

Spring不⽀持原型bean的循环依赖。单例bean通过setXxx或者@Autowired进⾏循环依赖。Spring的循环依赖的理论依据基于Java的引⽤传递,当获得对象的引⽤时,对象的属性是可以延后设置的,但是构造器必须是在获取引⽤之前。Spring通过setXxx或者@Autowired⽅法解决循环依赖其实是通过提前暴露⼀个ObjectFactory对象来完成的,简单来说ClassA在调⽤构造器完成对象初始化之后,在调⽤ClassAsetClassB⽅法之前就把ClassA实例化的对象通过ObjectFactory提前暴露到Spring容器中。

<bean name="mongoDao" class="xyz.coolblog.autowire.MongoDao"/>
<bean name="mysqlDao" class="xyz.coolblog.autowire.MySqlDao"/>

<!-- 非自动注入,手动配置依赖 -->
<bean name="service-without-autowire" class="xyz.coolblog.autowire.Service" autowire="no">
    <property name="mysqlDao" ref="mysqlDao"/>
    <property name="mongoDao" ref="mongoDao"/>
</bean>

<!-- 通过设置 autowire 属性,我们就不需要像上面那样显式配置依赖了 -->
<bean name="service-with-autowire" class="xyz.coolblog.autowire.Service" autowire="byName"/>

Spring容器类继承图

阅读源码的一些建议: Spring源码太多了太复杂,看着看着就迷失在了代码的海洋里。建议大家自己动手实现一个简单的IOC容器,通过实践,才会有更多的感悟。

转载请说明出处内容投诉
CSS教程_站长资源网 » Spring IOC 源码分析

发表评论

欢迎 访客 发表评论

一个令你着迷的主题!

查看演示 官网购买