美文网首页
spring 启动过程源码分析

spring 启动过程源码分析

作者: pingyilong | 来源:发表于2022-03-25 15:53 被阅读0次

    本章所有源码解析基于spring-framework-5.3.10版本进行分析

    在下面这行代码就完成了spring容器的初始化,后续将基于这行代码进行spring启动源码分析<br />AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);

    <a name="NDKgD"></a>

    1、AnnotationConfigApplicationContext的类定义及类结构图

    public class AnnotationConfigApplicationContext extends GenericApplicationContext implements AnnotationConfigRegistry {}
    
    image.png

    <a name="h1nkP"></a>

    2、AnnotationConfigApplicationContext构造方法

    AnnotationConfigApplicationContext参数为配置类,是可变长度数组,方法内部会执行无参构造方法,注册配置信息,完成扫描等步骤,具体详见以下代码注释

    public AnnotationConfigApplicationContext(Class<?>... componentClasses) {
            /**
             *
             * 会先调用父类无参构造方法创建一个BeanFactory
             * public GenericApplicationContext() {
             *      this.beanFactory = new DefaultListableBeanFactory();
             * }
             *
             * 1、执行无参数构造方法,在无参构造方法内会初始化:AnnotatedBeanDefinitionReader、ClassPathBeanDefinitionScanner
             *  1.1、初始化AnnotatedBeanDefinitionReader读取器,其中会注册以下6个spring的后置处理器类型的BeanDefinition:
             *          ConfigurationClassPostProcessor:它完成了对加了Configuration注解类的解析,@ComponentScan、@Import的解析
             *          AutowiredAnnotationBeanPostProcessor:用来处理@Autowired的注入
             *          CommonAnnotationBeanPostProcessor:用来处理如@Resource,@PostConstruct等符合JSR-250规范的注解
             *          PersistenceAnnotationBeanPostProcessor:来用支持JPA
             *          EventListenerMethodProcessor:用来处理方法上加了@EventListener注解的方法
             *          DefaultEventListenerFactory
             *  1.2、初始化ClassPathBeanDefinitionScanner,程序员可以外部调用ClassPathBeanDefinitionScanner#doScan(),或者可以继承该类重写scan规则来动态扫描注解;
             *      spring内部用的ClassPathBeanDefinitionScanner是重新new出来的
             *      其中会完成:注册@Component、@ManagedBean、@Named对应的AnnotationTypeFilter
             */
            this();
            /**
             * 将传入的配置类解析成BeanDefinition(实际类型为AnnotatedGenericBeanDefinition),然后放入到BeanDefinitionMap中,
             * 这样后面在ConfigurationClassPostProcessor中能解析配置类
             */
            register(componentClasses);
            refresh();
        }
    

    <a name="Tg5Ua"></a>

    3、refresh()

    refresh()是父类org.springframework.context.support.AbstractApplicationContext 中的方法,具体内容见以下代码及主要注释如下:

    @Override
        public void refresh() throws BeansException, IllegalStateException {
            synchronized (this.startupShutdownMonitor) {
                StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");
    
                // Prepare this context for refreshing.
                /**
                 * 做一些前期准备工作
                 * 1、为子类提供抽模板方法initPropertySources:子类可以把ServletContext中的参数对设置到Environment
                 * 2、校验环境变量属性
                 * 3、初始化earlyApplicationListeners
                 * 4、初始化earlyApplicationEvents
                 */
                prepareRefresh();
    
                // Tell the subclass to refresh the internal bean factory.
                /**
                 * 为子类提供refreshBeanFactory()方法,子类可以对BeanFactory进行一些操作与设置
                 */
                ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
                // Prepare the bean factory for use in this context.
                /**
                 * 准备BeanFactory
                 *  1. 设置BeanFactory的类加载器BeanClassLoader、SpringEL表达式解析器beanExpressionResolver、类型转化注册器PropertyEditorRegistrar
                 *  2. 添加三个BeanPostProcessor,注意是具体的BeanPostProcessor实例对象
                 *      2.1、ApplicationContextAwareProcessor:用来处理EnvironmentAware、EmbeddedValueResolverAware等回调setApplicationContext()方法
                 *      2.2、ApplicationListenerDetector:负责把实现了ApplicantsListener类型的Bean注册到ApplicationContext的监听列表
                 *      2.3、LoadTimeWeaverAwareProcessor:
                 *
                 *  3. 记录ignoreDependencyInterface:如果一个属性对应的set方法在ignoredDependencyInterfaces接口中被定义了,则该属性不会被spring进行自动注入
                 *      EnvironmentAware
                 *      EmbeddedValueResolverAware
                 *      ResourceLoaderAware
                 *      ApplicationEventPublisherAware
                 *      MessageSourceAware
                 *      ApplicationContextAware
                 *      ApplicationStartupAware
                 *
                 *  4. 记录ResolvableDependency
                 *      BeanFactory
                 *      ResourceLoader
                 *      ApplicationEventPublisher
                 *      ApplicationContext
                 *
                 *  5. 添加四个环境相关的单例Bean
                 *          5.1、environment
                 *          5.2、systemProperties
                 *          5.3、systemEnvironment
                 *          5.4、applicationStartup
                 */
                prepareBeanFactory(beanFactory);
    
                try {
                    // Allows post-processing of the bean factory in context subclasses.
                    /**
                     * 为子类提供的方法,子类可以对BeanFactory进行设置
                     * 此方法允许子类在所有的bean尚未初始化之前注册BeanPostProcessor。
                     *  通过XML和注解初始化无默认实现,
                     * 如果是WEB容器则此步会进行web容器scope(request、session、application)的注册和注册环境相关的bean等操作
                     */
                    postProcessBeanFactory(beanFactory);
    
                    StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
    
                    // Invoke factory processors registered as beans in the context.
                    /**
                     * 执行所有的BeanFactoryPostProcessor,包括自定义的和spring内置的,开始对BeanFactory进行处理
                     * 在此步骤内会将所有的bean对应的BeanDefinition解析出来放入到beanFactory的BeanDefinitionMap中
                     * 默认情况下,
                     *      BeanFactory中的BeanDefinitionMap中有6个BeanDefinition,5个基础的+配置类AppConfig
                     *      这6个中有一个BeanFactoryPostProcessor:ConfigurationClassPostProcessor,这个类主要是解析配置类,
                     *          配置类:1、加了 @Configuration注解的Full配置类
                     *                2、加了 @Component,@ComponentScan,@Import,@ImportResource,@Bean 注解的 Lite配置类
                     *      扫描的过程中可能又会扫描出其他的BeanFactoryPostProcessor,那么这些BeanFactoryPostProcessor也得在这一步执行
                     *
                     *
                     * BeanFactoryPostProcessors按入场方式分为:
                     * 1. 程序员调用ApplicationContext的API手动添加
                     * 2. Spring自己扫描出来的
                     *
                     * BeanFactoryPostProcessor按类型又可以分为:
                     * 1. 普通BeanFactoryPostProcessor
                     * 2. BeanDefinitionRegistryPostProcessor
                     *
                     * 执行顺序顺序如下:
                     * 1. 执行手动添加的BeanDefinitionRegistryPostProcessor                        的postProcessBeanDefinitionRegistry()方法
                     * 2. 执行扫描出来的BeanDefinitionRegistryPostProcessor + 实现了PriorityOrdered 的postProcessBeanDefinitionRegistry()方法
                     * 3. 执行扫描出来的BeanDefinitionRegistryPostProcessor + 实现了Ordered           的postProcessBeanDefinitionRegistry()方法
                     * 4. 执行扫描出来的BeanDefinitionRegistryPostProcessor + 普通                   的postProcessBeanDefinitionRegistry()方法
                     * 5. 执行扫描出来的BeanDefinitionRegistryPostProcessor + 所有                   的postProcessBeanFactory()方法
                     * 6. 执行手动添加的BeanFactoryPostProcessor                                   的postProcessBeanFactory()方法
                     * 7. 执行扫描出来的BeanFactoryPostProcessor + 实现了PriorityOrdered          的postProcessBeanFactory()方法
                     * 8. 执行扫描出来的BeanFactoryPostProcessor + 实现了Ordered                  的postProcessBeanFactory()方法
                     * 9. 执行扫描出来的BeanFactoryPostProcessor + 普通                          的postProcessBeanFactory()方法
                     *
                     * ConfigurationClassPostProcessor就会在第2步执行,会进行扫描
                     */
                    invokeBeanFactoryPostProcessors(beanFactory);
    
                    /**
                     * 扫描BeanPostProcessor实例化并排序,并添加到BeanFactory中的beanPostProcessor中
                     * 之前已经注册过三个
                     * 在这一步实例化BeanPostProcessor是因为BeanPostProcessor是用来干预bean的创建过程的,后面要实例化bean了,所以需要提前把所有的BeanPostProcessor实例化出来
                     *
                     * 扫描BeanPostProcessor顺序如下:
                     *  1、注册: PostProcessorRegistrationDelegate.BeanPostProcessorChecker
                     *  2、扫描并注册:实现PriorityOrdered接口的
                     *  3、扫描并注册:实现Ordered接口的
                     *  4、扫描并注册:未排序的
                     *  5、扫描并注册:MergedBeanDefinitionPostProcessor的
                     *  6、注册:ApplicationListenerDetector
                     */
                    registerBeanPostProcessors(beanFactory);
    
                    beanPostProcess.end();
    
                    // Initialize message source for this context.
                    // 设置ApplicationContext的MessageSource,要么是用户设置的,要么是DelegatingMessageSource
                    initMessageSource();
    
                    /**
                     * 初始化事件广播,作用是:发布事件,并且为所发布的事件找到对应的事件监听器。
                     * 设置ApplicationContext的applicationEventMulticaster,要么是用户设置的,要么是SimpleApplicationEventMulticaster
                     */
                    initApplicationEventMulticaster();
    
                    // Initialize other special beans in specific context subclasses.
                    // 给子类的模板方法,执行其他的初始化操作,如和SpringMVC整合时,需要初始化一些其他的bean,默认是一个空方法
                    onRefresh();
    
                    // 把定义的ApplicationListener的Bean对象,设置到ApplicationContext中去,并执行在此之前所发布的事件
                    registerListeners();
    
                    // Instantiate all remaining (non-lazy-init) singletons.
                    // 实例化其余的非懒加载的单例bean
                    finishBeanFactoryInitialization(beanFactory);
    
                    // Last step: publish corresponding event.
                    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();
                    contextRefresh.end();
                }
            }
        }
    

    以上针对refresh()方法做了一个大概的解析,refresh()方法中,最重要的是invokeBeanFactoryPostProcessors(beanFactory)和finishBeanFactoryInitialization(beanFactory)两个方法。

    • invokeBeanFactoryPostProcessors(beanFactory)方法中会扫描出所有的BeanDefinition
    • finishBeanFactoryInitialization(beanFactory)方法会完成所有的非懒加载的单例bean的初始化工作
      <a name="gqzKW"></a>

    3.1、finishBeanFactoryInitialization(beanFactory)

    此方法会完成所有的非懒加载的单例bean的初始化工作,具体的Bean初始化工作在beanFactory.preInstantiateSingletons()方法中完成

    
        /**
         * Finish the initialization of this context's bean factory,
         * initializing all remaining singleton beans.
         */
        protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
            // Initialize conversion service for this context.
            // 如果BeanFactory中存在名字叫conversionService的Bean,则设置为BeanFactory的conversionService属性
            // ConversionService是用来进行类型转化的,在Spring里其实就是把配置文件中的String转为其它类型,从3.0开始出现,目的和jdk的PropertyEditor接口是一样
            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));
            }
    
            // Register a default embedded value resolver if no BeanFactoryPostProcessor
            // (such as a PropertySourcesPlaceholderConfigurer bean) registered any before:
            // at this point, primarily for resolution in annotation attribute values.
            // 设置默认的占位符解析器  ${xxx}  ---key
            if (!beanFactory.hasEmbeddedValueResolver()) {
                beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
            }
    
            // Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
            String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
            for (String weaverAwareName : weaverAwareNames) {
                getBean(weaverAwareName);
            }
    
            // Stop using the temporary ClassLoader for type matching.
            beanFactory.setTempClassLoader(null);
    
            // Allow for caching all bean definition metadata, not expecting further changes.
            beanFactory.freezeConfiguration();
    
            // Instantiate all remaining (non-lazy-init) singletons.
            // 实例化非懒加载的单例Bean
            beanFactory.preInstantiateSingletons();
        }
    

    <a name="JjAHb"></a>

    beanFactory.preInstantiateSingletons();

    该方法是ConfigurableListableBeanFactory接口中的方法,具体实现在org.springframework.beans.factory.support.DefaultListableBeanFactory类中,在DefaultListableBeanFactory#preInstantiateSingletons方法中实现具体的初始化工作。<br />此方法中会完成所有的非懒加载的单例bean,或者FactoryBean是实现了SmartFactoryBean接口并且isEagerInit=true的对象的创建工作

    @Override
        public void preInstantiateSingletons() throws BeansException {
            if (logger.isTraceEnabled()) {
                logger.trace("Pre-instantiating singletons in " + this);
            }
            // Iterate over a copy to allow for init methods which in turn register new bean definitions.
            // While this may not be part of the regular factory bootstrap, it does otherwise work fine.
            List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
            // Trigger initialization of all non-lazy singleton beans...
            /**
             * 遍历所有的BeanDefinition,将所有的非懒加载的单例bean初始化
             */
            for (String beanName : beanNames) {
                // 获取合并后的BeanDefinition
                RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
                // 判断不是抽象的,单例的,非懒加载的
                if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
                    if (isFactoryBean(beanName)) {
                        /**
                         * FactoryBean:是一个特殊的bean,
                         * FactoryBean是一个接口,本身就是一个bean,他的名字是&开头的;该接口还有一个方法getObject()会返回真正的bean对象
                         */
                        // 如果是FactoryBean,获取FactoryBean对象
                        Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
                        if (bean instanceof FactoryBean) {
                            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) {
                                // 如果该FactoryBean是SmartFactoryBean接口的实现类或子接口,
                                // 并且isEagerInit()放回true则会在容器启动时候就将该bean创建,创建真正的Bean对象(getObject()返回的对象)
                                getBean(beanName);
                            }
                        }
                    }
                    else {
                        // 创建Bean对象
                        getBean(beanName);
                    }
                }
            }
    
            // 所有的非懒加载单例Bean都创建完了后
            // Trigger post-initialization callback for all applicable beans...
            for (String beanName : beanNames) {
                Object singletonInstance = getSingleton(beanName);
                if (singletonInstance instanceof SmartInitializingSingleton) {
                    StartupStep smartInitialize = this.getApplicationStartup().start("spring.beans.smart-initialize").tag("beanName", beanName);
                    SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
                    if (System.getSecurityManager() != null) {
                        AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
                            smartSingleton.afterSingletonsInstantiated();
                            return null;
                        }, getAccessControlContext());
                    }
                    else {
                        // 所有的非懒加载单例bean都创建完成之后调用
                        smartSingleton.afterSingletonsInstantiated();
                    }
                    smartInitialize.end();
                }
            }
        }
    
    

    <a name="iRFfm"></a>

    getMergedLocalBeanDefinition

    此方法位置为:<br />org.springframework.beans.factory.support.AbstractBeanFactory#getMergedLocalBeanDefinition<br />获取合并之后的BeanDefinition,合并之后的BeanDefinition会存在mergedBeanDefinitions这个map中,key为beanName,定义为:<br />private final Map<String, RootBeanDefinition> mergedBeanDefinitions = new ConcurrentHashMap<>(256);

    protected RootBeanDefinition getMergedLocalBeanDefinition(String beanName) throws BeansException {
            // Quick check on the concurrent map first, with minimal locking.
            RootBeanDefinition mbd = this.mergedBeanDefinitions.get(beanName);
            /**
             * stale:表示是否需要再进行重新合并
             * 如果mergedBeanDefinitions这个map中已经有合并之后的BeanDefinition并且不需要再次合并,则直接返回
             */
            if (mbd != null && !mbd.stale) {
                return mbd;
            }
            // 再次调用合并的方法
            return getMergedBeanDefinition(beanName, getBeanDefinition(beanName));
        }
    

    具体的合并操作方法如下:

    protected RootBeanDefinition getMergedBeanDefinition(String beanName, BeanDefinition bd, @Nullable BeanDefinition containingBd)
                throws BeanDefinitionStoreException {
    
            synchronized (this.mergedBeanDefinitions) {
                // 新创建一个合并之后的对象
                RootBeanDefinition mbd = null;
                RootBeanDefinition previous = null;
                
                // Check with full lock now in order to enforce the same merged instance.
                if (containingBd == null) {
                    mbd = this.mergedBeanDefinitions.get(beanName);
                }
                // 如果已合并的map中没有,或者需要重新进行合并,则进行合并操作
                if (mbd == null || mbd.stale) {
                    previous = mbd;
                    if (bd.getParentName() == null) {
                        // Use copy of given root bean definition.
                        // 如果该bd没有父BeanDefinition,则直接将本bd组装成新的RootBeanDefinition返回即可
                        if (bd instanceof RootBeanDefinition) {
                            mbd = ((RootBeanDefinition) bd).cloneBeanDefinition();
                        }
                        else {
                            mbd = new RootBeanDefinition(bd);
                        }
                    }
                    else {
                        // Child bean definition: needs to be merged with parent.
                        // pbd表示parentBeanDefinition
                        BeanDefinition pbd;
                        try {
                            String parentBeanName = transformedBeanName(bd.getParentName());
                            if (!beanName.equals(parentBeanName)) {
                                pbd = getMergedBeanDefinition(parentBeanName);
                            }
                            else {
                                BeanFactory parent = getParentBeanFactory();
                                if (parent instanceof ConfigurableBeanFactory) {
                                    pbd = ((ConfigurableBeanFactory) parent).getMergedBeanDefinition(parentBeanName);
                                }
                                else {
                                    throw new NoSuchBeanDefinitionException(parentBeanName,
                                            "Parent name '" + parentBeanName + "' is equal to bean name '" + beanName +
                                                    "': cannot be resolved without a ConfigurableBeanFactory parent");
                                }
                            }
                        }
                        catch (NoSuchBeanDefinitionException ex) {
                            throw new BeanDefinitionStoreException(bd.getResourceDescription(), beanName,
                                    "Could not resolve parent bean definition '" + bd.getParentName() + "'", ex);
                        }
    
                        // Deep copy with overridden values.
                        // 子BeanDefinition的属性覆盖父BeanDefinition的属性,这就是合并
                        mbd = new RootBeanDefinition(pbd);
                        mbd.overrideFrom(bd);
                    }
    
                    // Set default singleton scope, if not configured before.
                    if (!StringUtils.hasLength(mbd.getScope())) {
                        mbd.setScope(SCOPE_SINGLETON);
                    }
    
                    // A bean contained in a non-singleton bean cannot be a singleton itself.
                    // Let's correct this on the fly here, since this might be the result of
                    // parent-child merging for the outer bean, in which case the original inner bean
                    // definition will not have inherited the merged outer bean's singleton status.
                    if (containingBd != null && !containingBd.isSingleton() && mbd.isSingleton()) {
                        mbd.setScope(containingBd.getScope());
                    }
    
                    // Cache the merged bean definition for the time being
                    // (it might still get re-merged later on in order to pick up metadata changes)
                    if (containingBd == null && isCacheBeanMetadata()) {
                        this.mergedBeanDefinitions.put(beanName, mbd);
                    }
                }
                if (previous != null) {
                    copyRelevantMergedBeanDefinitionCaches(previous, mbd);
                }
                return mbd;
            }
        }
    

    <a name="bi4W2"></a>

    getBean

    在getBean方法中会调用doGetBean()完成获取bean的相关操作,具体实现方法<br />org.springframework.beans.factory.support.AbstractBeanFactory#doGetBean

    @Override
        public Object getBean(String name) throws BeansException {
            return doGetBean(name, null, null, false);
        }
    
    @SuppressWarnings("unchecked")
        protected <T> T doGetBean(String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly)
                throws BeansException {
    
            // name有可能是 &xxx 或者 xxx,如果name是&xxx,那么beanName就是xxx
            // name有可能传入进来的是别名,那么beanName就是id
            String beanName = transformedBeanName(name);
            Object beanInstance;
    
            // Eagerly check singleton cache for manually registered singletons.
            Object sharedInstance = getSingleton(beanName);
            if (sharedInstance != null && args == null) {
                if (logger.isTraceEnabled()) {
                    if (isSingletonCurrentlyInCreation(beanName)) {
                        logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
                                "' that is not fully initialized yet - a consequence of a circular reference");
                    }
                    else {
                        logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
                    }
                }
                // 如果sharedInstance是FactoryBean,那么就调用getObject()返回对象
                beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, null);
            }
    
            else {
                // Fail if we're already creating this bean instance:
                // We're assumably within a circular reference.
                if (isPrototypeCurrentlyInCreation(beanName)) {
                    throw new BeanCurrentlyInCreationException(beanName);
                }
    
                // Check if bean definition exists in this factory.
                BeanFactory parentBeanFactory = getParentBeanFactory();
                if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
                    // Not found -> check parent.
                    // &&&&xxx---->&xxx
                    String nameToLookup = originalBeanName(name);
                    if (parentBeanFactory instanceof AbstractBeanFactory) {
                        return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
                                nameToLookup, requiredType, args, typeCheckOnly);
                    }
                    else if (args != null) {
                        // Delegation to parent with explicit args.
                        return (T) parentBeanFactory.getBean(nameToLookup, args);
                    }
                    else if (requiredType != null) {
                        // No args -> delegate to standard getBean method.
                        return parentBeanFactory.getBean(nameToLookup, requiredType);
                    }
                    else {
                        return (T) parentBeanFactory.getBean(nameToLookup);
                    }
                }
    
                if (!typeCheckOnly) {
                    markBeanAsCreated(beanName);
                }
    
                StartupStep beanCreation = this.applicationStartup.start("spring.beans.instantiate")
                        .tag("beanName", name);
                try {
                    if (requiredType != null) {
                        beanCreation.tag("beanType", requiredType::toString);
                    }
                    RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
    
                    // 检查BeanDefinition是不是Abstract的
                    checkMergedBeanDefinition(mbd, beanName, args);
    
                    // Guarantee initialization of beans that the current bean depends on.
                    String[] dependsOn = mbd.getDependsOn();
                    if (dependsOn != null) {
                        // dependsOn表示当前beanName所依赖的,当前Bean创建之前dependsOn所依赖的Bean必须已经创建好了
                        for (String dep : dependsOn) {
                            // beanName是不是被dep依赖了,如果是则出现了循环依赖
                            if (isDependent(beanName, dep)) {
                                throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                        "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
                            }
                            // dep被beanName依赖了,存入dependentBeanMap中,dep为key,beanName为value
                            registerDependentBean(dep, beanName);
    
                            // 创建所依赖的bean
                            try {
                                getBean(dep);
                            }
                            catch (NoSuchBeanDefinitionException ex) {
                                throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                        "'" + beanName + "' depends on missing bean '" + dep + "'", ex);
                            }
                        }
                    }
    
                    // Create bean instance.
                    if (mbd.isSingleton()) {
                        sharedInstance = getSingleton(beanName, () -> {
                            try {
                                return createBean(beanName, mbd, args);
                            }
                            catch (BeansException ex) {
                                // Explicitly remove instance from singleton cache: It might have been put there
                                // eagerly by the creation process, to allow for circular reference resolution.
                                // Also remove any beans that received a temporary reference to the bean.
                                destroySingleton(beanName);
                                throw ex;
                            }
                        });
                        beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
                    }
                    else if (mbd.isPrototype()) {
                        // It's a prototype -> create a new instance.
                        Object prototypeInstance = null;
                        try {
                            beforePrototypeCreation(beanName);
                            prototypeInstance = createBean(beanName, mbd, args);
                        }
                        finally {
                            afterPrototypeCreation(beanName);
                        }
                        beanInstance = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
                    }
                    else {
                        String scopeName = mbd.getScope();
                        if (!StringUtils.hasLength(scopeName)) {
                            throw new IllegalStateException("No scope name defined for bean ´" + beanName + "'");
                        }
                        Scope scope = this.scopes.get(scopeName);
                        if (scope == null) {
                            throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
                        }
                        try {  // session.getAttriute(beaName)  setAttri
                            Object scopedInstance = scope.get(beanName, () -> {
                                beforePrototypeCreation(beanName);
                                try {
                                    return createBean(beanName, mbd, args);
                                }
                                finally {
                                    afterPrototypeCreation(beanName);
                                }
                            });
                            beanInstance = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
                        }
                        catch (IllegalStateException ex) {
                            throw new ScopeNotActiveException(beanName, scopeName, ex);
                        }
                    }
                }
                catch (BeansException ex) {
                    beanCreation.tag("exception", ex.getClass().toString());
                    beanCreation.tag("message", String.valueOf(ex.getMessage()));
                    cleanupAfterBeanCreationFailure(beanName);
                    throw ex;
                }
                finally {
                    beanCreation.end();
                }
            }
    
            // 检查通过name所获得到的beanInstance的类型是否是requiredType
            return adaptBeanInstance(name, beanInstance, requiredType);
        }
    

    <a name="VurzF"></a>

    doGetBean()

    doGetBean()方法内部会调用createBean()方法进行bean的创建工作

    @Override
        protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
                throws BeanCreationException {
    
            if (logger.isTraceEnabled()) {
                logger.trace("Creating instance of bean '" + beanName + "'");
            }
            RootBeanDefinition mbdToUse = mbd;
    
            // Make sure bean class is actually resolved at this point, and
            // clone the bean definition in case of a dynamically resolved Class
            // which cannot be stored in the shared merged bean definition.
            // 马上就要实例化Bean了,确保beanClass被加载了
            Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
            if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
                mbdToUse = new RootBeanDefinition(mbd);
                mbdToUse.setBeanClass(resolvedClass);
            }
    
            // Prepare method overrides.
            try {
                mbdToUse.prepareMethodOverrides();
            }
            catch (BeanDefinitionValidationException ex) {
                throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
                        beanName, "Validation of method overrides failed", ex);
            }
    
            try {
                // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
                // 实例化前
                Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
                if (bean != null) {
                    return bean;
                }
            }
            catch (Throwable ex) {
                throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
                        "BeanPostProcessor before instantiation of bean failed", ex);
            }
    
            try {
                Object beanInstance = doCreateBean(beanName, mbdToUse, args);
                if (logger.isTraceEnabled()) {
                    logger.trace("Finished creating instance of bean '" + beanName + "'");
                }
                return beanInstance;
            }
            catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
                // A previously detected exception with proper bean creation context already,
                // or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
                throw ex;
            }
            catch (Throwable ex) {
                throw new BeanCreationException(
                        mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
            }
        }
    

    <a name="dCOXc"></a>

    createBean()

    createBean()方法内部又会调用doCreateBean()方法完成具体bean的创建工作

    protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
                throws BeanCreationException {
    
            // 实例化bean
            // Instantiate the bean.
            BeanWrapper instanceWrapper = null;
            if (mbd.isSingleton()) {
                // 有可能在本Bean创建之前,就有其他Bean把当前Bean给创建出来了(比如依赖注入过程中)
                instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
            }
            if (instanceWrapper == null) {
                // 创建Bean实例,完成对象创建,还不是bean
                instanceWrapper = createBeanInstance(beanName, mbd, args);
            }
            Object bean = instanceWrapper.getWrappedInstance();
            Class<?> beanType = instanceWrapper.getWrappedClass();
            if (beanType != NullBean.class) {
                mbd.resolvedTargetType = beanType;
            }
    
            // 后置处理合并后的BeanDefinition
            // Allow post-processors to modify the merged bean definition.
            synchronized (mbd.postProcessingLock) {
                if (!mbd.postProcessed) {
                    try {
                        applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
                    }
                    catch (Throwable ex) {
                        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                "Post-processing of merged bean definition failed", ex);
                    }
                    mbd.postProcessed = true;
                }
            }
    
            // 为了解决循环依赖提前缓存单例创建工厂
            // Eagerly cache singletons to be able to resolve circular references
            // even when triggered by lifecycle interfaces like BeanFactoryAware.
            boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
                    isSingletonCurrentlyInCreation(beanName));
            if (earlySingletonExposure) {
                if (logger.isTraceEnabled()) {
                    logger.trace("Eagerly caching bean '" + beanName +
                            "' to allow for resolving potential circular references");
                }
                // 循环依赖-添加到三级缓存
                addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
            }
    
            // Initialize the bean instance.
            Object exposedObject = bean;
            try {
                // 属性填充
                populateBean(beanName, mbd, instanceWrapper);  //getBean()
    
                // 初始化,执行各种生命周期回调方法和aop等
                exposedObject = initializeBean(beanName, exposedObject, mbd);
            }
            catch (Throwable ex) {
                if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
                    throw (BeanCreationException) ex;
                }
                else {
                    throw new BeanCreationException(
                            mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
                }
            }
    
            if (earlySingletonExposure) {
                Object earlySingletonReference = getSingleton(beanName, false);
                if (earlySingletonReference != null) {
                    if (exposedObject == bean) {
                        exposedObject = earlySingletonReference;
                    }
                    else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
                        // beanName被哪些bean依赖了,现在发现beanName所对应的bean对象发生了改变,那么则会报错
                        String[] dependentBeans = getDependentBeans(beanName);
                        Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
                        for (String dependentBean : dependentBeans) {
                            if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
                                actualDependentBeans.add(dependentBean);
                            }
                        }
                        if (!actualDependentBeans.isEmpty()) {
                            throw new BeanCurrentlyInCreationException(beanName,
                                    "Bean with name '" + beanName + "' has been injected into other beans [" +
                                    StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
                                    "] in its raw version as part of a circular reference, but has eventually been " +
                                    "wrapped. This means that said other beans do not use the final version of the " +
                                    "bean. This is often the result of over-eager type matching - consider using " +
                                    "'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.");
                        }
                    }
                }
            }
    
            // Register bean as disposable.
            try {
                // Bean 销毁相关
                registerDisposableBeanIfNecessary(beanName, bean, mbd);
            }
            catch (BeanDefinitionValidationException ex) {
                throw new BeanCreationException(
                        mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
            }
    
            return exposedObject;
        }
    

    相关文章

      网友评论

          本文标题:spring 启动过程源码分析

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