Spring框架注解开发——FactoryBean源码解析

用Debug进入IOC容器

AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AopConfig.class);

进入Refresh方法

this.refresh();

调用this.finishBeanFactoryInitialization(beanFactory)方法

在遍历获取容器中所有Bean,依次获取

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

    List<String> beanNames = new ArrayList(this.beanDefinitionNames);
    Iterator var2 = beanNames.iterator();

GetBean——>DogetBean——>getSingleton

注意创建Bean不是一下就创建的 

 1)先从缓存中创建Bean,如果能获取到,说明Bean是被创建过的,直接使用

如果没有从缓存中获取,在创建Bean,只要创建的Bean都会被缓存

2)createBean,创建Bean  

注意【BeanPostProcessor】是对象创建完成,初始化前后调用的

【InstantiationAwareBeanPostProcessor】是创建对象前调用的后置处理器

try {
    beanInstance = this.resolveBeforeInstantiation(beanName, mbdToUse);
    if (beanInstance != null) {
        return beanInstance;
    }
} catch (Throwable var8) {
    throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName, "BeanPostProcessor before instantiation of bean failed", var8);
}

resolveBeforeInstantiation 希望后置处理器能返回一个代理对象 

如果不能返回resolveBeforeInstantiation,就会执行

beanInstance = this.doCreateBean(beanName, mbdToUse, args);
if (this.logger.isDebugEnabled()) {
    this.logger.debug("Finished creating instance of bean '" + beanName + "'");
}

resolveBeforeInstantiation 执行流程

protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
    Object bean = null;
    if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
        if (!mbd.isSynthetic() && this.hasInstantiationAwareBeanPostProcessors()) {
            Class<?> targetType = this.determineTargetType(beanName, mbd);
            if (targetType != null) {
                bean = this.applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
                if (bean != null) {
                    bean = this.applyBeanPostProcessorsAfterInitialization(bean, beanName);
                }
            }
        }

        mbd.beforeInstantiationResolved = bean != null;
    }

 后置处理器先尝试返回对象 this.applyBeanPostProcessorsBeforeInstantiation

拿到所有的后置处理器,如果是InstantiationAwareBeanPostProcessor处理器,执行postProcessBeforeInstantiation方法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值