国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專欄INFORMATION COLUMN

Spring Ioc的原理解析之getBean流程分析

Jiavan / 921人閱讀

摘要:簡單介紹模塊和模塊是框架的基礎部分,提供控制反轉和依賴注入特性。

Spring Framework簡單介紹

Core Container模塊:Core 和 Beans 模塊是框架的基礎部分,提供 IoC (控制反轉)和 DI(依賴注入)特性。 Context構建于Core 和 Bean 之上,提供了一個BeanFactory來訪問應用組件,添加了國際化(例如資源綁定)、事件傳播、資源加載等。SpEL提供了強大的表達式語言。

Data Access/Integration模塊:JDBC提供了一個JDBC抽象層,ORM對象關系映射如:JPA,XOM提供了一個ObjectXML映射關系,JMS提供了生產消息和消費消息的功能,Transactions:提供了編程和聲明性的事務管理,這些事務類必須實現特定的接口。

Web模塊:提供了面向Web的特性,比如Spring Mvc,使用servlet listeners初始化IoC容器以及一個面向Web的應用上下文,典型的父子容器關系。

Aop模塊:Aspects模塊提供了對AspectJ集成的支持。Instrumentation模塊提供了class instrumentation支持和classloader實現,動態字節碼插樁。

Test模塊:Test模塊支持使用Junit等對Spring組件進行測試


Ioc的核心思想以及常用注解和應用

Ioc的核心思想:資源組件不由使用方管理,而由不使用資源的第三方管理,這可以帶來很多好處。第一,資源集中管理,實現資源的可配置和易管理。第二,降低了使用資源雙方的依賴程度,也就是我們說的耦合度

常用的注解:

@Configuration 相對于配置文件中的
@Bean 相對于配置文件中的
@CompentScan 包掃描
@Scope 配置Bean的作用域
@Lazy 是否開啟懶加載
@Conditional 條件注解 spring boot中經常用到
@Import 導入組件
......

應用:

    package com.toby.ioc.iocprinciple;
    
    import org.springframework.beans.factory.annotation.Autowired;
    
   
    public class PrincipleAspect {
        @Autowired
        private PrincipleLog principleLog;
    
        /*public PrincipleLog getPrincipleLog() {
            return principleLog;
        }
    
        public void setPrincipleLog(PrincipleLog principleLog) {
            this.principleLog = principleLog;
        }*/
    }
    package com.toby.ioc.iocprinciple;
    
    public class PrincipleBean {
    }
    package com.toby.ioc.iocprinciple;
    
    import org.springframework.beans.factory.annotation.Autowire;
    import org.springframework.context.annotation.*;
    
    @Configuration
    @ComponentScan(basePackages = {"com.toby.ioc.iocprinciple"})
    //@ImportResource("classpath:Beans.xml")
    @Import(PrincipleService.class)
    public class PrincipleConfig {
        @Bean
        public PrincipleBean principleBean(){
            return new PrincipleBean();
        }
    
        //@Bean(autowire = Autowire.BY_TYPE)
        @Bean
        public PrincipleAspect principleAspect(){
            return new PrincipleAspect();
        }
    
        @Bean
        @Primary
        public PrincipleLog principleLog(){
            return new PrincipleLog();
        }
    
        @Bean
        public PrincipleLog principleLog2(){
            return new PrincipleLog();
        }
    }
    package com.toby.ioc.iocprinciple;
    
    import org.springframework.stereotype.Controller;
    
    @Controller
    public class PrincipleController {
    }
    package com.toby.ioc.iocprinciple;
    
    import org.springframework.stereotype.Repository;
    
    @Repository
    public class PrincipleDao {
    }
    package com.toby.ioc.iocprinciple;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    
    /**
     * @desc: 循環依賴
     * @author: toby
     */
    @Component
    public class PrincipleInstanceA {
        @Autowired
        private PrincipleInstanceB instanceB;
    }
    package com.toby.ioc.iocprinciple;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    
    /**
     * @desc: 循環依賴
     * @author: toby
     */
    @Component
    public class PrincipleInstanceB {
        @Autowired
        private PrincipleInstanceA instanceA;
    }
    package com.toby.ioc.iocprinciple;
    
    /**
     * @desc:
     * @author: toby
     */
    public class PrincipleLog {
    }
    package com.toby.ioc.iocprinciple;
    
    /**
     * @desc:
     * @author: toby
     */
    public class PrincipleService {
    }
    package com.toby.ioc.iocprinciple;
    
    import org.springframework.context.annotation.AnnotationConfigApplicationContext;
    
    /**
     * @desc: ioc原理解析 啟動
     * @author: toby
     */
    public class PrincipleMain {
        public static void main(String[] args) {
            AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(PrincipleConfig.class);
            /*for (String beanDefinitionName : context.getBeanDefinitionNames()) {
                System.out.println("bean定義名稱:" + beanDefinitionName);
            }*/
            PrincipleAspect principleAspect = context.getBean(PrincipleAspect.class);
            context.close();
            System.out.println(principleAspect);
        }
    }

完整的代碼請見:spring

getBean的源碼解析

beanfactory的類繼承圖:

首先創建org.springframework.context.annotation.AnnotationConfigApplicationContext#AnnotationConfigApplicationContext(java.lang.Class...)

    public AnnotationConfigApplicationContext(Class... annotatedClasses) {
        //主要的作用往容器中注冊系統級別的處理器,為處理我們自定義的配置類準備,以及初始化classpath下的bean定義掃描
        this();
        //注冊我們自定義的配置類
        register(annotatedClasses);
        //Ioc容器刷新12大步
        refresh();
   }

org.springframework.context.support.AbstractApplicationContext#refresh 12大步

public void refresh() throws BeansException, IllegalStateException {
        synchronized (this.startupShutdownMonitor) {
            //1:準備刷新上下文環境
            prepareRefresh();

            //2:獲取初始化Bean工廠
            ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

            //3:對bean工廠進行填充屬性
            prepareBeanFactory(beanFactory);
            try {
                //4:Spring開放接口 留給子類去實現該接口
                postProcessBeanFactory(beanFactory);

                //:5:調用我們的bean工廠的后置處理器
                invokeBeanFactoryPostProcessors(beanFactory);

                // 6:注冊我們bean后置處理器
                registerBeanPostProcessors(beanFactory);

                // 7:初始化國際化資源處理器
                initMessageSource();

                //8:初始化事件多播器
                initApplicationEventMulticaster();

                //9:// 這個方法同樣也是留個子類實現的springboot也是從這個方法進行啟動tomcat的.
                onRefresh();

                //10:把我們的事件監聽器注冊到多播器上
                registerListeners();

                //11:實例化所有的非懶加載的單實例bean
                finishBeanFactoryInitialization(beanFactory);

                //12:最后刷新容器 發布刷新事件(Spring cloud eureka也是從這里啟動的)
                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();
            }
        }
    }

第11步:實例化所有的非懶加載的單實例bean
org.springframework.context.support.AbstractApplicationContext#finishBeanFactoryInitialization

protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
        // Initialize conversion service for this context.
        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 bean post-processor
        // (such as a PropertyPlaceholderConfigurer bean) registered any before:
        // at this point, primarily for resolution in annotation attribute values.
        if (!beanFactory.hasEmbeddedValueResolver()) {
            beanFactory.addEmbeddedValueResolver(new StringValueResolver() {
                @Override
                public String resolveStringValue(String strVal) {
                    return 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);

        //凍結所有的bean定義
        beanFactory.freezeConfiguration();
        
        //實例化剩余的非懶加載的單實例bean
        beanFactory.preInstantiateSingletons();
    }

實例化剩余的非懶加載的單實例bean:

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

        // 獲取容器中所有beanName
        List beanNames = new ArrayList(this.beanDefinitionNames);

        //觸發實例化所有的非懶加載的單實例bean
        for (String beanName : beanNames) {
            //合并bean定義
            RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
            //非抽象,單實例,非懶加載
            if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
                //是否工廠bean,是要獲取factorybean的getObject方法
                if (isFactoryBean(beanName)) {
                    //factorybean的bean那么前面加了一個FACTORY_BEAN_PREFIX就是&
                    final FactoryBean factory = (FactoryBean) getBean(FACTORY_BEAN_PREFIX + beanName);
                    boolean isEagerInit;
                    if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
                        isEagerInit = AccessController.doPrivileged(new PrivilegedAction() {
                            @Override
                            public Boolean run() {
                                return ((SmartFactoryBean) factory).isEagerInit();
                            }
                        }, getAccessControlContext());
                    }
                    else {
                        isEagerInit = (factory instanceof SmartFactoryBean &&
                                ((SmartFactoryBean) factory).isEagerInit());
                    }
                    if (isEagerInit) {
                        //調用getBean流程
                        getBean(beanName);
                    }
                }
                else {//非工廠bean
                    //調用getBean流程
                    getBean(beanName);
                }
            }
        }

        //觸發初始化之后的回調,到這里所有的bean都存放在了單例緩沖池中了
        for (String beanName : beanNames) {
            Object singletonInstance = getSingleton(beanName);
            if (singletonInstance instanceof SmartInitializingSingleton) {
                final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
                if (System.getSecurityManager() != null) {
                    AccessController.doPrivileged(new PrivilegedAction() {
                        @Override
                        public Object run() {
                            smartSingleton.afterSingletonsInstantiated();
                            return null;
                        }
                    }, getAccessControlContext());
                }
                else {
                    //觸發實例化之后的方法afterSingletonsInstantiated
                    smartSingleton.afterSingletonsInstantiated();
                }
            }
        }
    }

getBean流程
org.springframework.beans.factory.support.AbstractBeanFactory#getBean(java.lang.String)

public Object getBean(String name) throws BeansException {
        //獲取bean
        return doGetBean(name, null, null, false);
    }

org.springframework.beans.factory.support.AbstractBeanFactory#doGetBean

protected  T doGetBean(
            final String name, final Class requiredType, final Object[] args, boolean typeCheckOnly)
            throws BeansException {
        //轉化bean名稱
        final String beanName = transformedBeanName(name);
        Object bean;

        // Eagerly check singleton cache for manually registered singletons.
        //先從單例緩沖池中獲取,第一次肯定沒有,后面都有
        Object sharedInstance = getSingleton(beanName);
        if (sharedInstance != null && args == null) {
            if (logger.isDebugEnabled()) {
                if (isSingletonCurrentlyInCreation(beanName)) {
                    logger.debug("Returning eagerly cached instance of singleton bean "" + beanName +
                            "" that is not fully initialized yet - a consequence of a circular reference");
                }
                else {
                    logger.debug("Returning cached instance of singleton bean "" + beanName + """);
                }
            }
            //為什么不直接返回,原因就是可能是FactoryBean
            bean = 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.
                String nameToLookup = originalBeanName(name);
                if (args != null) {
                    // Delegation to parent with explicit args.
                    return (T) parentBeanFactory.getBean(nameToLookup, args);
                }
                else {
                    // No args -> delegate to standard getBean method.
                    return parentBeanFactory.getBean(nameToLookup, requiredType);
                }
            }

            if (!typeCheckOnly) {
                markBeanAsCreated(beanName);
            }

            try {
                //合并bean定義
                final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
                //檢查當前創建的bean定義是不是抽象
                checkMergedBeanDefinition(mbd, beanName, args);

                //處理依賴bean,獲取依賴bean名稱
                String[] dependsOn = mbd.getDependsOn();
                if (dependsOn != null) {
                    for (String dep : dependsOn) {
                        if (isDependent(beanName, dep)) {
                            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                    "Circular depends-on relationship between "" + beanName + "" and "" + dep + """);
                        }
                        //保存的是依賴和beanName之間的映射關系
                        registerDependentBean(dep, beanName);
                        try {
                            //獲取依賴的bean
                            getBean(dep);
                        }
                        catch (NoSuchBeanDefinitionException ex) {
                            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                    """ + beanName + "" depends on missing bean "" + dep + """, ex);
                        }
                    }
                }

                //創建單例bean
                if (mbd.isSingleton()) {
                    //把beanName 和一個singletonFactory匿名內部類傳入用于回調
                    sharedInstance = getSingleton(beanName, new ObjectFactory() {
                        @Override
                        public Object getObject() throws BeansException {
                            try {
                                //創建bean
                                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;
                            }
                        }
                    });
                    bean = 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);
                    }
                    bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
                }

                else {
                    String scopeName = mbd.getScope();
                    final 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, new ObjectFactory() {
                            @Override
                            public Object getObject() throws BeansException {
                                beforePrototypeCreation(beanName);
                                try {
                                    return createBean(beanName, mbd, args);
                                }
                                finally {
                                    afterPrototypeCreation(beanName);
                                }
                            }
                        });
                        bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
                    }
                    catch (IllegalStateException ex) {
                        throw new BeanCreationException(beanName,
                                "Scope "" + scopeName + "" is not active for the current thread; consider " +
                                "defining a scoped proxy for this bean if you intend to refer to it from a singleton",
                                ex);
                    }
                }
            }
            catch (BeansException ex) {
                cleanupAfterBeanCreationFailure(beanName);
                throw ex;
            }
        }

        // Check if required type matches the type of the actual bean instance.
        if (requiredType != null && bean != null && !requiredType.isInstance(bean)) {
            try {
                return getTypeConverter().convertIfNecessary(bean, requiredType);
            }
            catch (TypeMismatchException ex) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Failed to convert bean "" + name + "" to required type "" +
                            ClassUtils.getQualifiedName(requiredType) + """, ex);
                }
                throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
            }
        }
        return (T) bean;
    }

createBean:
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBean(java.lang.String, org.springframework.beans.factory.support.RootBeanDefinition, java.lang.Object[])

protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException {
        if (logger.isDebugEnabled()) {
            logger.debug("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.
        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);
        }
        //干活的do方法,真正的創建我們的bean的實例對象的過程
        Object beanInstance = doCreateBean(beanName, mbdToUse, args);
        if (logger.isDebugEnabled()) {
            logger.debug("Finished creating instance of bean "" + beanName + """);
        }
        return beanInstance;
    }

doCreateBean
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean

protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)
            throws BeanCreationException {

        //實例化BeanWrapper是對Bean的包裝
        BeanWrapper instanceWrapper = null;
        if (mbd.isSingleton()) {
            instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
        }
        if (instanceWrapper == null) {
            //選擇合適的實例化策略來創建新的實例:工廠方法、構造函數自動注入、簡單初始化
            instanceWrapper = createBeanInstance(beanName, mbd, args);
        }
        //獲取早期對象,所謂的早期對象就是還沒有初始化的對象
        final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
        Class beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);
        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;
            }
        }

        //是否暴露早期對象,默認是
        boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
                isSingletonCurrentlyInCreation(beanName));
        if (earlySingletonExposure) {
            if (logger.isDebugEnabled()) {
                logger.debug("Eagerly caching bean "" + beanName +
                        "" to allow for resolving potential circular references");
            }
            //把我們的早期對象包裝成一個singletonFactory對象 該對象提供了一個getObject方法
            addSingletonFactory(beanName, new ObjectFactory() {
                @Override
                public Object getObject() throws BeansException {
                    return getEarlyBeanReference(beanName, mbd, bean);
                }
            });
        }

        // Initialize the bean instance.
        Object exposedObject = bean;
        try {
            //給我們的屬性進行賦值(調用set方法進行賦值)
            populateBean(beanName, mbd, instanceWrapper);
            if (exposedObject != null) {
                //初始化,動態代理也在這里生成
                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 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 " +
                                ""getBeanNamesOfType" 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;
    }

initializeBean
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#initializeBean(java.lang.String, java.lang.Object, org.springframework.beans.factory.support.RootBeanDefinition)

protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
        if (System.getSecurityManager() != null) {
            AccessController.doPrivileged(new PrivilegedAction() {
                @Override
                public Object run() {
                    invokeAwareMethods(beanName, bean);
                    return null;
                }
            }, getAccessControlContext());
        }
        else {
            //我們的bean實現了XXXAware接口進行方法的回調
            invokeAwareMethods(beanName, bean);
        }

        Object wrappedBean = bean;
        if (mbd == null || !mbd.isSynthetic()) {
            //調用我們的bean的后置處理器的postProcessorsBeforeInitialization方法 注意@PostConstruct在這步處理調用
            wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
        }

        try {
            //調用初始化方法,比如實現了InitializingBean接口,回調InitializingBean的afterPropertiesSet()方法或者調用自定義的init方法
            invokeInitMethods(beanName, wrappedBean, mbd);
        }
        catch (Throwable ex) {
            throw new BeanCreationException(
                    (mbd != null ? mbd.getResourceDescription() : null),
                    beanName, "Invocation of init method failed", ex);
        }
        if (mbd == null || !mbd.isSynthetic()) {
            //調用我們bean的后置處理器的PostProcessorsAfterInitialization方法
            wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
        }
        return wrappedBean;
    }

getBean的流程圖如下

文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。

轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/75789.html

相關文章

  • Spring IOC 容器源碼分析 - 循環依賴解決辦法

    摘要:實例化時,發現又依賴于。一些緩存的介紹在進行源碼分析前,我們先來看一組緩存的定義。可是看完源碼后,我們似乎仍然不知道這些源碼是如何解決循環依賴問題的。 1. 簡介 本文,我們來看一下 Spring 是如何解決循環依賴問題的。在本篇文章中,我會首先向大家介紹一下什么是循環依賴。然后,進入源碼分析階段。為了更好的說明 Spring 解決循環依賴的辦法,我將會從獲取 bean 的方法getB...

    aikin 評論0 收藏0
  • 仿照 Spring 實現簡單 IOC 和 AOP - 下篇

    摘要:在上文中,我實現了一個很簡單的和容器。比如,我們所熟悉的就是在這里將切面邏輯織入相關中的。初始化的工作算是結束了,此時處于就緒狀態,等待外部程序的調用。其中動態代理只能代理實現了接口的對象,而動態代理則無此限制。 1. 背景 本文承接上文,來繼續說說 IOC 和 AOP 的仿寫。在上文中,我實現了一個很簡單的 IOC 和 AOP 容器。上文實現的 IOC 和 AOP 功能很單一,且 I...

    AlexTuan 評論0 收藏0
  • Spring IOC 容器源碼分析 - 填充屬性到 bean 原始對象

    摘要:源碼分析源碼一覽本節,我們先來看一下填充屬性的方法,即。所有的屬性值是在方法中統一被注入到對象中的。檢測是否存在與相關的或。這樣可以在很大程度上降低源碼分析的難度。若候選項是非類型,則表明已經完成了實例化,此時直接返回即可。 1. 簡介 本篇文章,我們來一起了解一下 Spring 是如何將配置文件中的屬性值填充到 bean 對象中的。我在前面幾篇文章中介紹過 Spring 創建 bea...

    SKYZACK 評論0 收藏0
  • Spring專題Bean初始化源碼分析(1)

    摘要:初始化我們知道容器初始化后會對容器中非懶加載的,單例的以及非抽象的定義進行的初始化操作,所以我們分析源碼的入口也就是在容器初始化的入口,分析容器初始化后在什么地方開始第一次的初始化。 前言 Spring IOC容器在初始化之后會對容器中非懶加載的,單例的以及非抽象的bean定義進行bean的初始化操作,同時會也涉及到Bean的后置處理器以及DI(依賴注入)等行為。對于Bean的初始化,...

    harryhappy 評論0 收藏0
  • 零基礎帶你看Spring源碼——IOC控制反轉

    摘要:依賴注入是向某個類或方法注入一個值,其中所用到的原理就是控制反轉。但發現更多時間是在調和的源碼。里面就是從中取出這個,完成控制反轉的。控制反轉的優點最后來以我個人觀點談談控制反轉的優點吧。控制反轉為了降低項目耦合,提高延伸性。 本章開始來學習下Spring的源碼,看看Spring框架最核心、最常用的功能是怎么實現的。網上介紹Spring,說源碼的文章,大多數都是生搬硬推,都是直接看來的...

    wing324 評論0 收藏0

發表評論

0條評論

最新活動
閱讀需要支付1元查看
<