美文网首页
spring bean 的生命周期

spring bean 的生命周期

作者: Mattle | 来源:发表于2021-06-29 08:10 被阅读0次

    前置:

    1.实例化 Instantiation 创建一个空对象
    2.属性赋值 Populate 为对象填充属性
    3.初始化 Initialization 为对象属性初始化 前置处理 -->后置处理(AOP)
    4.销毁 Destruction 销毁bean

    spring三级缓存

        // 一级缓存 单例池  保存单例对象。 key: beanName value:bean 
        private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
    
        // 二级缓存 工厂池   key: beanName value:beanFactory
        private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);
    
       // 三级缓存,循环对象依赖列表 元对象池 在getSingleton()时会一级一级的判断 并且加入
        private final Map<String, Object> earlySingletonObjects = new ConcurrentHashMap<>(16);
    

    1:从doGetBean开始

        protected <T> T doGetBean(
                String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly)
                throws BeansException {
                    // 得到beanName的全路径
            String beanName = transformedBeanName(name);
            Object beanInstance;
    
            // Eagerly check singleton cache for manually registered singletons.
            // 从缓存中查询当是不是由相关的bean
            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 + "'");
                    }
                }
                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);
                }
            ... // 此处省略父工厂 相关的代码
                    // 单例
                    if (mbd.isSingleton()) {
                        sharedInstance = getSingleton(beanName, () -> {
                            try {
                                return createBean(beanName, mbd, args);
                            }
                            catch (BeansException ex) {
                                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 {
                            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();
                }
            }
            return adaptBeanInstance(name, beanInstance, requiredType);
        }
    

    2:doGetBean 之后便是 doCreateBean

        protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
                throws BeanCreationException {
    
            // Instantiate the bean.
            BeanWrapper instanceWrapper = null;
            if (mbd.isSingleton()) {
                instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
            }
            if (instanceWrapper == null) {
                instanceWrapper = createBeanInstance(beanName, mbd, args);
            }
            Object bean = instanceWrapper.getWrappedInstance();
            Class<?> beanType = instanceWrapper.getWrappedClass();
            if (beanType != NullBean.class) {
                mbd.resolvedTargetType = beanType;
            }
    
            // 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 {
                // 比较重要的一步,为bean填充属性 Autowire 在这里实现 主要封装了 PropertyValues
                populateBean(beanName, mbd, instanceWrapper);
                // 初始化bean 主要操作 前置处理 -> invokeInitMethods() 调用初始化方法 -> 后置处理:(在后置处理里 发生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)) {
                        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 {
                registerDisposableBeanIfNecessary(beanName, bean, mbd);
            }
            catch (BeanDefinitionValidationException ex) {
                throw new BeanCreationException(
                        mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
            }
    
            return exposedObject;
        }
    

    3:总结
    1:applicationContent.getBean() 时 依次从一级二级三级缓存中获取,如果没有该bean,则加入三级缓存。
    2:调用BeanFactory的getObject()方法在回调里 createBean()调用 doCreateBean(), 在populateBean()填充属性之前 加入二级缓存池。工厂池。
    3:populateBean()里主要针对Autowire 做处理。(按名称优先于按类型处理) PropertyValues,对bean的属性和属性值做处理。
    4:initializeBean()方法里主要是对 前置处理器 -> 触发InitializeBean初始化方法->后置处理器。
    前置处理器 主要对 一些 Ware感知做处理、相关方法 applyBeanPostProcessorsBeforeInitialization()
    初始化方法 invokeInitMethods() 对 InitializeBean 处理 afterPropertiesSet 指定初始化方法
    后置处理器 主要对AOP做处理。拿到代理对象 相关方法 applyBeanPostProcessorsAfterInitialization()
    5:doCreateBean之后 调用 removeSingletonIfCreatedForTypeCheckOnly()移除一级缓存、

    相关文章

      网友评论

          本文标题:spring bean 的生命周期

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