Spring启动流程核心步骤: 2、obtainFreshBeanFactory()

本文详细探讨了Spring启动流程中的核心步骤——obtainFreshBeanFactory(),包括初始化容器、处理器和beanDefinition加载。主要关注在GenericApplicationContext和AbstractRefreshableApplicationContext中的实现,并指出在Spring Boot及注解启动时,beanDefinition加载不在此过程进行,而是通过其他方式完成。同时提到了ignoreDependencyInterface和ignoreDependencyType方法的解释,以及加载BeanDefinition的具体过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

2、初始化容器、初始化处理器、加载beanDefinition信息

protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {

   refreshBeanFactory();

   return getBeanFactory();

}

有两种实现 :

    1、先看咱们项目中注解方式启动采用的GenericApplicationContext

@Override

protected final void refreshBeanFactory() throws IllegalStateException {

    //直接返回默认的容器

   if (!this.refreshed.compareAndSet(false, true)) {

      throw new IllegalStateException(

            "GenericApplicationContext does not support multiple refresh attempts: just call 'refresh' once");

   }

   this.beanFactory.setSerializationId(getId());

}    

 

   2、再看AbstractRefreshableApplicationContext中获取容器的过程

@Override

protected final void refreshBeanFactory() throws BeansException {

   if (hasBeanFactory()) {

      destroyBeans();

      closeBeanFactory();

   }

   try {

      DefaultListableBeanFactory beanFactory = createBeanFactory();

      beanFactory.setSerializationId(getId());

      customizeBeanFactory(beanFactory); //对BeanFactory//是否支持Beandefinition属性覆盖和是否支持循环依赖

      loadBeanDefinitions(beanFactory);  //详见下边介绍

      synchronized (this.beanFactoryMonitor) {

         this.beanFactory = beanFactory;

      }

   }catch (IOException ex) {

      throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);

   }

}

 

protected DefaultListableBeanFactory createBeanFactory() {

    //创建BeanFactory如果存在父容器则指定父容器、

    // 并设置忽略的类BeanNameAware.class、BeanFactoryAware.class、BeanClassLoaderAware.class;这里是重点。忽略自动装配。这里指定的都是接口。什么意思?   

    // ignoreDependencyInterface具体下边链接文章介绍

   return new DefaultListableBeanFactory(getInternalParentBeanFactory());

}

 

 详见: ignoreDependencyInterface和ignoreDependencyType(Class<?> type)详解

protected void customizeBeanFactory(DefaultListableBeanFactory beanFactory) {

   if (this.allowBeanDefinitionOverriding != null) {

      beanFactory.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);

   }

   if (this.allowCircularReferences != null) {

      beanFactory.setAllowCircularReferences(this.allowCircularReferences);

   }

}

 

 loadBeanDefinitions(beanFactory):

现在Springboot 启动和采用注解启动时,都不在这个地方进行包的扫描和加载。

    

详见: 加载BeanDefinition的过程分析  此处是对AnnotationConfigWebApplicationContext中的加载类信息的解读。

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值