Spring读取Bean的过程

本文详细解析了Spring中Bean的加载过程,从缓存获取到实例化,涉及单例、原型bean的创建,循环依赖的处理,以及FactoryBean的应用。核心步骤包括:检查别名、从singletonCache获取bean、实例化bean、处理循环依赖、调用父BeanFactory、创建bean、处理依赖、转换对象类型等。
摘要由CSDN通过智能技术生成

Spring中Bean加载的过程是一个关键的步骤。这个过程主要是通过BeanFactoyr中的getBean方法来实现的。具体的方法是在AbstractBeanFactory方法中实现的。getBean方法主要有两个功能,首先是去缓存中读取bean,如果没有就实例化这个bean,实例化bean的过程是一个将GenericBeanDefinition转变为一个正式的bean的过程。
具体实现的方法是:

protected <T> T doGetBean(final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly)

Spring代码中有个特点是所有的具体执行的代码都是以do 开头。

protected <T> T doGetBean(
            final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly)
            throws BeansException {

        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 + "'");
                }
            }
            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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值