资讯专栏INFORMATION COLUMN

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

Jiavan / 850人阅读

摘要:简单介绍模块和模块是框架的基础部分,提供控制反转和依赖注入特性。

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的流程图如下

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/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元查看
<