美文网首页
Spring IOC BeanFactory 源码分析

Spring IOC BeanFactory 源码分析

作者: Kohler | 来源:发表于2018-08-17 23:19 被阅读123次

    IOC 概念

    • BeanFactory 。基础类型IoC容器,提供完整的IoC服务支持。
    • ApplicationContext 。 ApplicationContext 在 BeanFactory 的基础上构建,是相对比较高级的容器实现,除了拥有 BeanFactory 的所有支持, ApplicationContext 还提供了其他高级特性,比如事件发布、国际化信息支持等

    本篇只讲BeanFactory

    IOC 容器 BeanFactory

    这里不采用xml方式,而是手动注册BeanDefinition,更加清晰 Bean 的构建过程,略过繁琐的xml解析过程。

    public static void main(String[] args) {
        DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
    
        RootBeanDefinition userDefinition = new RootBeanDefinition(UserServiceImpl.class);
        RootBeanDefinition accountDefinition = new RootBeanDefinition(AccountServiceImpl.class);
        RootBeanDefinition integralDefinition = new RootBeanDefinition(IntegralServiceImpl.class);
    
        // 注册BeanDefinition
        beanFactory.registerBeanDefinition("userService", userDefinition);
        beanFactory.registerBeanDefinition("accountService", accountDefinition);
        beanFactory.registerBeanDefinition("integralDefinition", integralDefinition);
    
        // 1.构造方法注入方式
        ConstructorArgumentValues argValues = new ConstructorArgumentValues();
        argValues.addIndexedArgumentValue(0, integralDefinition);
        userDefinition.setConstructorArgumentValues(argValues);
    
        //2.setter方法注入方式
        MutablePropertyValues propertyValues = new MutablePropertyValues();
        propertyValues.addPropertyValue("accountService", new RuntimeBeanReference("accountService"));
        userDefinition.setPropertyValues(propertyValues);
    
        UserService userService = beanFactory.getBean("userService", UserService.class);
        System.out.println(userService.getName());
        System.out.println(userService.getMoney());
        System.out.println(userService.getIntegral());
    }
    

    注册BeanDefinition

    // 1、校验
    // 2、检测是否已经通过其他方式注册过,如果是,则判断是否可以覆盖等等。
    // 3、已经开始创建bean,加锁
    this.beanDefinitionMap.put(beanName, beanDefinition);
    this.beanDefinitionNames.add(beanName);
    

    添加属性依赖

    BeanDefinition 中设置依赖

    • 构造方法注入

    • setter方法注入

      需要提供setter方法

    如下

    public UserServiceImpl(IntegralService integralService) {
        this.integralService = integralService;
    }
    public void setAccountService(AccountService accountService) {
        this.accountService = accountService;
    }
    

    创建获取bean

    因为 BeanFactory 采用延迟加载的机制,bean 不会随着容器的初始化而初始化,而是在获取 bean 的时候去容器和父容器中查找,若找不到,便会查找相应的 BeanDefination ,并构建 bean。

    AbstractBeanFactory#doGetBean

    protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
          @Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
    
        // name可能是别名或者是FactoryBean名字,获取真实bean名字
       final String beanName = transformedBeanName(name);
       Object bean;
    
       // 查找已经注册的bean,这个getSingleton方法是解决循环依赖的关键点。
       Object sharedInstance = getSingleton(beanName);
       if (sharedInstance != null && args == null) {
           // 根据获取的bean是否是FactoryBean,去直接返回还是调用FactoryBean#getObject
          bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
       }
    
       else {
          // 当前bean是 Prototype 并且正在创建,说明循环引用,报错
          // 这里的逻辑是 BeanFactory 创建bean的过程中都会将beanName放在一个集合中(Prototype型是放在ThreadLocal中),完成后会移掉,创建bean的过程中,若是发现集合中存在当前正在创建的bean,则说明该bean创建的过程中,间接引用到自身,构成循环引用。
          if (isPrototypeCurrentlyInCreation(beanName)) {
             throw new BeanCurrentlyInCreationException(beanName);
          }
    
          // bean definition 不在自己中,且parentBeanFactory存在,则在parentBeanFactory中查找
          BeanFactory parentBeanFactory = getParentBeanFactory();
          if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
             // 调用parentBeanFactory的getBean方法,逻辑一样
              ...
          }
    
          if (!typeCheckOnly) {
             markBeanAsCreated(beanName);
          }
    
          try {
              // 像xml配置中可以设置继承,在这里合并BeanDefinition,
             final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
             checkMergedBeanDefinition(mbd, beanName, args);
    
             // 确保初始化当前bean所依赖的bean。
             String[] dependsOn = mbd.getDependsOn();
             if (dependsOn != null) {
                ...
             }
    
             // 创建单例bean
             if (mbd.isSingleton()) {
                 // 创建、获取单例,后面分析
                sharedInstance = getSingleton(beanName, () -> {
                   try {
                      return createBean(beanName, mbd, args);
                   }
                   catch (BeansException ex) {
                      // 显式地从单例缓存中删除实例:它可能是由创建过程早期地放在那里的,以允许循环引用解析。并且删除收到对bean的临时引用的任何bean。
                      destroySingleton(beanName);
                      throw ex;
                   }
                });
                // 根据获取的bean是否是FactoryBean,去直接返回还是调用FactoryBean#getObject
                bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
             }
    
              // 创建 Prototype bean
             else if (mbd.isPrototype()) {
                // prototype是每次获取时创建
                Object prototypeInstance = null;
                try {
                   beforePrototypeCreation(beanName);
                   prototypeInstance = createBean(beanName, mbd, args);
                }
                finally {
                   afterPrototypeCreation(beanName);
                }
                bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
             }
    
              // 其他Scope,在BeanFactory中只有"singleton"和"prototype"两种,默认为"singleton",其他的scope都是实现Scope接口,并通过 registerScope 方法注册,像RequestScope、SessionScope等,通过Scope的实现获取bean,是一种策略模式
             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, () -> {
                      beforePrototypeCreation(beanName);
                      try {
                         return createBean(beanName, mbd, args);
                      }
                      finally {
                         afterPrototypeCreation(beanName);
                      }
                   });
                   bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
                }
                catch (IllegalStateException ex) {
                   throw new BeanCreationException(...);
                }
             }
          }
          catch (BeansException ex) {
             cleanupAfterBeanCreationFailure(beanName);
             throw ex;
          }
       }
    
       // 检查所需的类型是否与实际bean实例的类型匹配。返回需要的类型
       if (requiredType != null && !requiredType.isInstance(bean)) {
          try {
             T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
             if (convertedBean == null) {
                throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
             }
             return convertedBean;
          }
          catch (TypeMismatchException ex) {
             // log
          }
       }
       return (T) bean;
    }
    

    DefaultSingletonBeanRegistry#getSingleton(java.lang.String, boolean)方法是解决bean循环依赖的关键点,方法代码

    protected Object getSingleton(String beanName, boolean allowEarlyReference) {
       Object singletonObject = this.singletonObjects.get(beanName);
       if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
          synchronized (this.singletonObjects) {
             singletonObject = this.earlySingletonObjects.get(beanName);
             if (singletonObject == null && allowEarlyReference) {
                ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
                if (singletonFactory != null) {
                   singletonObject = singletonFactory.getObject();
                   this.earlySingletonObjects.put(beanName, singletonObject);
                   this.singletonFactories.remove(beanName);
                }
             }
          }
       }
       return singletonObject;
    }
    

    对于创建bean的过程单独分析。

    创建单例

    // 返回以给定名称已注册的(原始,可能为FactoryBean)单例对象,如果还没有注册,创建并且注册一个新的。
    public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
            Assert.notNull(beanName, "Bean name must not be null");
        synchronized (this.singletonObjects) {
            Object singletonObject = this.singletonObjects.get(beanName);
            if (singletonObject == null) {
                // 当前创建的bean正在销毁
                if (this.singletonsCurrentlyInDestruction) {
                    throw new BeanCreationNotAllowedException(...);
                }
                // singletonsCurrentlyInCreation集合添加当前正在构建的beanName,如果添加失败,则当前bean正在创建,则抛异常 -> 循环引用
                beforeSingletonCreation(beanName);
                boolean newSingleton = false;
                boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
                if (recordSuppressedExceptions) {
                    this.suppressedExceptions = new LinkedHashSet<>();
                }
                try {
                    // 调用传入的工厂获取object
                    singletonObject = singletonFactory.getObject();
                    newSingleton = true;
                }
                catch ...
                finally {
                    if (recordSuppressedExceptions) {
                        this.suppressedExceptions = null;
                    }
                    // singletonsCurrentlyInCreation集合移除当前正在构建的beanName
                    afterSingletonCreation(beanName);
                }
                if (newSingleton) {
                    // 新建的bean注册到容器中
                    addSingleton(beanName, singletonObject);
                }
            }
            return singletonObject;
        }
    }
    protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException {
        // log
        RootBeanDefinition mbdToUse = mbd;
    
        // 直接获取class或者根据类名获取class
        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(...);
        }
    
        try {
            // 让BeanPostProcessors有机会返回一个代理而不是目标bean实例。
            // InstantiationAwareBeanPostProcessor拦截bean的构建,返回值不为空,则直接返回
            Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
            if (bean != null) {
                return bean;
            }
        }
        catch (Throwable ex) {
            throw new BeanCreationException(...);
        }
    
        try {
            // 真正构建bean
            Object beanInstance = doCreateBean(beanName, mbdToUse, args);
            if (logger.isDebugEnabled()) {
                logger.debug("Finished creating instance of bean '" + beanName + "'");
            }
            return beanInstance;
        }
        catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
            // A previously detected exception with proper bean creation context already,
            // or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
            throw ex;
        }
        catch (Throwable ex) {
            throw new BeanCreationException(...);
        }
    }
    
    

    AbstractAutowireCapableBeanFactory#doCreateBean方法

    这个方法是真正创建bean的方法,流程如下

    image
    protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
          throws BeanCreationException {
    
       // 实例化bean,BeanFactory中以BeanWrapper包装bean以及bean的一些信息
       BeanWrapper instanceWrapper = null;
       if (mbd.isSingleton()) {
          instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
       }
       if (instanceWrapper == null) {
          // 实例化bean对象
          instanceWrapper = createBeanInstance(beanName, mbd, args);
       }
       // 原始的bean实例
       final Object bean = instanceWrapper.getWrappedInstance();
       Class<?> beanType = instanceWrapper.getWrappedClass();
       if (beanType != NullBean.class) {
          mbd.resolvedTargetType = beanType;
       }
    
       // 允许PostProcessor修改合并的bean definition,MergedBeanDefinitionPostProcessor修改
       synchronized (mbd.postProcessingLock) {
          if (!mbd.postProcessed) {
             try {
                applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
             }
             catch (Throwable ex) {
                throw new BeanCreationException(...);
             }
             mbd.postProcessed = true;
          }
       }
    
       // 此时bean实例已经存在,但是对bean后续尚未完成,此时提前将bean暴露出来,是为了解决bean的循环引用
       boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
             isSingletonCurrentlyInCreation(beanName));
       if (earlySingletonExposure) {
          // log
          addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
       }
    
       //初始化bean实例。
       Object exposedObject = bean;
       try {
          // 填充bean属性
          populateBean(beanName, mbd, instanceWrapper);
          // 1、检查Aware接口并注入依赖
          // 2、调用容器中BeanPostProcessor#postProcessBeforeInitialization方法
          // 3、是InitializingBean,则调用afterPropertiesSet方法
          // 4、有自定义initMethodName方法,则调用
          // 5、调用容器中BeanPostProcessor#postProcessAfterInitialization方法
          exposedObject = initializeBean(beanName, exposedObject, mbd);
       }
       catch (Throwable 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<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
                for (String dependentBean : dependentBeans) {
                   if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
                      actualDependentBeans.add(dependentBean);
                   }
                }
                // 还是有依赖未解决,报错
                if (!actualDependentBeans.isEmpty()) {
                   throw new BeanCurrentlyInCreationException(...);
                }
             }
          }
       }
    
       // 注册销毁回调接口
       try {
          registerDisposableBeanIfNecessary(beanName, bean, mbd);
       }
       catch (BeanDefinitionValidationException ex) {
          throw new BeanCreationException(...);
       }
    
       return exposedObject;
    }
    

    每一个步骤单独分析

    1、实例化bean对象

    AbstractAutowireCapableBeanFactory#createBeanInstance

    // 为指定的bean创建一个新实例,使用适当的实例化策略:工厂方法、构造函数或简单实例化。 
    protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
        // 解析bean class
        Class<?> beanClass = resolveBeanClass(mbd, beanName);
    
        if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
    "Bean class isn't public, and non-public access not allowed: " + beanClass.getName());}
    
        // 有指定的Supplier获取bean
        Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
        if (instanceSupplier != null) {
            return obtainFromSupplier(instanceSupplier, beanName);
        }
        // 有配置指定的工厂方法
        if (mbd.getFactoryMethodName() != null)  {
            return instantiateUsingFactoryMethod(beanName, mbd, args);
        }
    
        // 检查是否已解析构造器
        boolean resolved = false;
        boolean autowireNecessary = false;
        if (args == null) {
            synchronized (mbd.constructorArgumentLock) {
                if (mbd.resolvedConstructorOrFactoryMethod != null) {
                    resolved = true;
                    autowireNecessary = mbd.constructorArgumentsResolved;
                }
            }
        }
        if (resolved) {
            if (autowireNecessary) {
                return autowireConstructor(beanName, mbd, null, null);
            }
            else {
                return instantiateBean(beanName, mbd);
            }
        }
    
        // SmartInstantiationAwareBeanPostProcessor拦截决定Constructors
        Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
        if (ctors != null ||
            mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR ||
            mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args))  {
            // 构造函数autowire
            return autowireConstructor(beanName, mbd, ctors, args);
        }
    
        // 没有特殊处理:简单地使用无参数构造函数。
        return instantiateBean(beanName, mbd);
    }
    

    构造函数依赖时会去查找、构建依赖的bean,若此时循环引用则抛出异常,因为此时本bean的构建已开始但尚未实例化,bean容器中找不到本bean的实例,又不可能再去重新创建一个同类型的bean,所以容器无法解决此依赖。

    2、设置Bean属性

    AbstractAutowireCapableBeanFactory#populateBean

    // 为bean实例填充在bean definition中定义的属性
    protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
        ...
    
        // InstantiationAwareBeanPostProcessor#postProcessAfterInstantiation 拦截bean属性的填充,在
        // doCreateBean之前InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation
        // 拦截beande构造
        ...
            
        PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
    
        if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
            mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
            MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
    
            // 根据名称添加属性值。
            if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
                autowireByName(beanName, mbd, bw, newPvs);
            }
    
            // 根据类型添加属性值。
            if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
                autowireByType(beanName, mbd, bw, newPvs);
            }
    
            pvs = newPvs;
        }
    
        boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
        boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE);
    
        if (hasInstAwareBpps || needsDepCheck) {
            if (pvs == null) {
                pvs = mbd.getPropertyValues();
            }
            PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
            if (hasInstAwareBpps) {
                for (BeanPostProcessor bp : getBeanPostProcessors()) {
                    if (bp instanceof InstantiationAwareBeanPostProcessor) {
                        InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                        pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
                        if (pvs == null) {
                            return;
                        }
                    }
                }
            }
            if (needsDepCheck) {
                checkDependencies(beanName, mbd, filteredPds, pvs);
            }
        }
    
        if (pvs != null) {
            // 填充依赖属性
            applyPropertyValues(beanName, mbd, bw, pvs);
        }
    }
    

    AbstractAutowireCapableBeanFactory#initializeBean方法包括包括了5个步骤:检查Aware接口并注入依赖、调用容器中BeanPostProcessor#postProcessBeforeInitialization方法、是InitializingBean,则调用afterPropertiesSet方法、有自定义initMethodName方法,则调用、调用容器中BeanPostProcessor#postProcessAfterInitialization方法

    3、检查Aware接口并注入依赖

    private void invokeAwareMethods(final String beanName, final Object bean) {
       if (bean instanceof Aware) {
          if (bean instanceof BeanNameAware) {
             ((BeanNameAware) bean).setBeanName(beanName);
          }
          if (bean instanceof BeanClassLoaderAware) {
             ClassLoader bcl = getBeanClassLoader();
             if (bcl != null) {
                ((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
             }
          }
          if (bean instanceof BeanFactoryAware) {
             ((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
          }
       }
    }
    

    这里检查bean是否实现BeanNameAwareBeanClassLoaderAwareBeanFactoryAware接口,如果有实现,则调用接口方法,设置相应的属性,Aware接口的其他子类并未在此设置,在 ApplicationContext 中有很多其他的Aware,一般通过给下一步的 BeanPostProcessors 添加 BeanPostProcessor ,然后由相应的 Processor 处理,伪码如下:

    public class MyBeanPostProcessor implements BeanPostProcessor {
        @Override
        public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
            if (bean instanceof Aware) {
                if (bean instanceof MyAware) {
                    ((MyAware) bean).process();
                }
            }
            return null;
        }
    }
    

    4、BeanPostProcessor 前置处理

    public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
          throws BeansException {
    
       Object result = existingBean;
       for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
          Object current = beanProcessor.postProcessBeforeInitialization(result, beanName);
          if (current == null) {
             return result;
          }
          result = current;
       }
       return result;
    }
    

    遍历beanPostProcessors,调用其前置处理方法。如果前置方法不返回空,则把返回结果设为当前bean,这里是Spring AOP 的实现点,只要在 beanProcessor 的前置方法返回传入的 bean 的代理对象,代理对象实现 bean 增强,那么后续使用将调用该 bean 增强后的方法,也就完成了切面的工作,同理 beanProcessor 的后置方法也能完成同样的工作。

    5、调用init方法

    // 所以属性设置完,开始初始化
    protected void invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd)
                throws Throwable {
    
        // 实现了InitializingBean 接口,则调用afterPropertiesSet方法
        boolean isInitializingBean = (bean instanceof InitializingBean);
        if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
            ...
            ((InitializingBean) bean).afterPropertiesSet();
            ...
        }
    
        if (mbd != null && bean.getClass() != NullBean.class) {
            String initMethodName = mbd.getInitMethodName();
            // 有自定义InitMethodName,则反射调用,完成初始化
            if (StringUtils.hasLength(initMethodName) &&
                !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
                !mbd.isExternallyManagedInitMethod(initMethodName)) {
                invokeCustomInitMethod(beanName, bean, mbd);
            }
        }
    }
    

    InitializingBean的继承结构中可以看到,InitializingBean的实现类还是很多的,也就说明在 Spring 内部bean的初始化都在其afterPropertiesSet方法内。在看Spring MVC源码的时候,RequestMappingHandlerMapping在处理 Controller 请求路径映射时便是在afterPropertiesSet中处理的。

    6、BeanPostProcessor 后置处理

    后置处理和前置处理类似

    7、注册销毁回调接口

    如果bean实现了DisposableBean或者AutoCloseable接口,或者有自定义的destroyMethodName属性,或者有DestructionAwareBeanPostProcessor判断需要销毁bean,则将bean注册到相应的销毁集合中,在容器 shutdown 或者调用destroySingletons(),方法的时候将会销毁

    //将给定的bean添加到工厂的可销毁bean列表中
    protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {
        AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null);
        if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) {
            if (mbd.isSingleton()) {
                // 注册到销毁bean集合中
                registerDisposableBean(beanName,
                                       new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
            }
            else {
                // 注册到自定义的scope中
                Scope scope = this.scopes.get(mbd.getScope());
                if (scope == null) {
                    throw new IllegalStateException("No Scope registered for scope name '" + mbd.getScope() + "'");
                }
                scope.registerDestructionCallback(beanName,
                                                  new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
            }
        }
    }
    // 判断是否需要添加到销毁bean的集合中
    protected boolean requiresDestruction(Object bean, RootBeanDefinition mbd) {
       return (bean.getClass() != NullBean.class &&
             (DisposableBeanAdapter.hasDestroyMethod(bean, mbd) || (hasDestructionAwareBeanPostProcessors() &&
                   DisposableBeanAdapter.hasApplicableProcessors(bean, getBeanPostProcessors()))));
    }
    

    那么到此一个bean的构建就完成了。返回bean容器的bean。

    总结

    • bean由BeanDefinition定义,BeanDefinition注册到BeanDefinitionRegistry中
    • BeanFactory是“懒加载”机制,获取bean的时候才去查找,若无,则创建
    • InstantiationAwareBeanPostProcessor 处理时机为bean实例化前后,可以拦截bean的实例化
    • Prototype型,在创建bean之前先将beanName放在一个Set中(在ThreadLocal中)创建完成移除。如果Set已存在该beanName,则说明存在循环引用,如A -> B -> ... -> A
    • Singleton型,singletonsCurrentlyInCreation集合在BeanFactory中,创建之前若此集合中存在该beanName则循环引用
    • 如果bean是含参构造函数,则先解决参数依赖,若此时参数依赖当前bean则直接报错,因当前bean无法实例化,也就无法提前暴露到singletonFactories中,所以容器无法解决
    • 属性依赖的bean,通过获取提前暴露到singletonFactories的singletonFactory,调用方法获取bean实例,完成依赖
    • Aware接口完成系统注入,BeanFactory包括3个:BeanNameAware、BeanClassLoaderAware、BeanFactoryAware,自定义可以通过BeanPostProcessor完成
    • InitializingBean接口及自定义initMethodName属性完成bean的初始化
    • BeanPostProcessor 处理时机为bean实例化之后,初始化前后,可以处理并替换bean(AOP实现)
    • DisposableBean接口、AutoCloseable接口及destroyMethodName属性完成bean的销毁工作
    • 容器中保存的是bean的包装BeanWrapper

    相关文章

      网友评论

          本文标题:Spring IOC BeanFactory 源码分析

          本文链接:https://www.haomeiwen.com/subject/folxiftx.html