关于spring:Spring依赖处理过程源码分析

57次阅读

共计 10678 个字符,预计需要花费 27 分钟才能阅读完成。

  1. AbstractAutowireCapableBeanFactory#doCreateBean 创立 Bean
  2. AbstractAutowireCapableBeanFactory#populateBean 属性的外围注入办法
  3. InstantiationAwareBeanPostProcessor#postProcessProperties 用于给 bean 解决值注入,@Autowire 就在这个过程解决注入
  4. InjectionMetadata#inject–>AutowiredMethodElement#inject
  5. resolveDependency
  6. doResolveDependency

AbstractAutowireCapableBeanFactory#doCreateBean 创立 Bean

protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, 
        final @Nullable Object[] args) throws BeanCreationException {
    // 1. 实例化 Bean,结构器注入或工厂办法注入
    BeanWrapper instanceWrapper = createBeanInstance(beanName, mbd, args);
    
    // 2. 后置处理器批改 Bean 的定义 BeanDefinition:bdp#postProcessMergedBeanDefinition
    applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
   
    // 3. 提前将 Bean 裸露到 IoC 容器中,用于解决循环依赖
    boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences 
                                      && isSingletonCurrentlyInCreation(beanName));
    if (earlySingletonExposure) {addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
    }
    
    // 4. populateBean 属性注入的外围办法,initializeBean 则执行 bean 初始化办法
    Object exposedObject = bean;
    populateBean(beanName, mbd, instanceWrapper);
    exposedObject = initializeBean(beanName, exposedObject, mbd);
    
    // 5. 注册 bean 的依赖关系,用于 bean 销毁用
    registerDisposableBeanIfNecessary(beanName, bean, mbd);
    return exposedObject;
}

AbstractAutowireCapableBeanFactory#populateBean 属性的外围注入办法

protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
    // 1. 判断是否须要进行属性注入:ibp#postProcessAfterInstantiation
    if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {for (BeanPostProcessor bp : getBeanPostProcessors()) {if (bp instanceof InstantiationAwareBeanPostProcessor) {InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {return;}
            }
        }
    }

    PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);

    // 2. 主动注入:包含名称注入和类型注入
    int resolvedAutowireMode = mbd.getResolvedAutowireMode();
    if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
        // 2.1 主动依据名称注入
        if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {autowireByName(beanName, mbd, bw, newPvs);
        }
        // 2.2 主动依据类型注入
        if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {autowireByType(beanName, mbd, bw, newPvs);
        }
        pvs = newPvs;
    }

    boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
    boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);

    // 3. 注解注入:后置处理器 ibp#postProcessProperties,赫赫有名的 @Autowired 就是在这解决的。PropertyDescriptor[] filteredPds = null;
    if (hasInstAwareBpps) {if (pvs == null) {pvs = mbd.getPropertyValues();
        }
        for (BeanPostProcessor bp : getBeanPostProcessors()) {if (bp instanceof InstantiationAwareBeanPostProcessor) {InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
                if (pvsToUse == null) {if (filteredPds == null) {filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
                    }
                    pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
                    if (pvsToUse == null) {return;}
                }
                pvs = pvsToUse;
            }
        }
    }
    // 4. 依赖查看,循环依赖...
    if (needsDepCheck) {if (filteredPds == null) {filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
        }
        checkDependencies(beanName, mbd, filteredPds, pvs);
    }

    // 5. 手动依赖注入
    if (pvs != null) {applyPropertyValues(beanName, mbd, bw, pvs);
    }
}

InstantiationAwareBeanPostProcessor#postProcessProperties 用于给 bean 解决值注入,@Autowire 就在这个过程解决注入

@Override
    public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
       // 这里获取指标 bean 每个须要注入的依赖,metadata 会蕴含一组元素,每个元素对应一个指标 bean :
       // 1. @Autowired/@Value 注解的属性 或者
       // 2. @Autowired/@Value 注解的办法参数
        InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs);
        try {
           // 执行依赖注入
            metadata.inject(bean, beanName, pvs);
        }
        catch (BeanCreationException ex) {throw ex;}
        catch (Throwable ex) {
            throw new BeanCreationException(beanName, "Injection of autowired dependencies failed", 
                                            ex);
        }
        return pvs;
    }

InjectionMetadata#inject–>AutowiredMethodElement#inject

public void inject(Object target, @Nullable String beanName, @Nullable PropertyValues pvs) 
            throws Throwable {
        Collection<InjectedElement> checkedElements = this.checkedElements;
        Collection<InjectedElement> elementsToIterate =
                (checkedElements != null ? checkedElements : this.injectedElements);
        if (!elementsToIterate.isEmpty()) {
            // 遍历指标 bean 每个须要注入的成员属性依赖或者成员办法参数依赖,执行相应的依赖注入
            for (InjectedElement element : elementsToIterate) {if (logger.isTraceEnabled()) {logger.trace("Processing injected element of bean'" + beanName + "':" + element);
                }
                element.inject(target, beanName, pvs);
            }
        }
    }


@Override
        protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) 
            throws Throwable {Field field = (Field) this.member;
            Object value;
            if (this.cached) {value = resolvedCachedArgument(beanName, this.cachedFieldValue);
            }
            else {DependencyDescriptor desc = new DependencyDescriptor(field, this.required);
                desc.setContainingClass(bean.getClass());
                Set<String> autowiredBeanNames = new LinkedHashSet<>(1);
                Assert.state(beanFactory != null, "No BeanFactory available");
                TypeConverter typeConverter = beanFactory.getTypeConverter();
                try {
                    // 依赖解析应用 beanFactory#resolveDependency
                    value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, 
                        typeConverter);
                }
                catch (BeansException ex) {
                    throw new UnsatisfiedDependencyException(null, beanName, 
                        new InjectionPoint(field), ex);
                }
                synchronized (this) {if (!this.cached) {if (value != null || this.required) {
                            this.cachedFieldValue = desc;
                            registerDependentBeans(beanName, autowiredBeanNames);
                            if (autowiredBeanNames.size() == 1) {String autowiredBeanName = autowiredBeanNames.iterator().next();
                                if (beanFactory.containsBean(autowiredBeanName) &&
                                        beanFactory.isTypeMatch(autowiredBeanName, field.getType())) {
                                    this.cachedFieldValue = new ShortcutDependencyDescriptor(desc, autowiredBeanName, field.getType());
                                }
                            }
                        }
                        else {this.cachedFieldValue = null;}
                        this.cached = true;
                    }
                }
            }
            if (value != null) {ReflectionUtils.makeAccessible(field);
                field.set(bean, value);
            }
        }

Spring 中依赖解决从 DefaultListableBeanFactory 的 resolveDependency 办法开始解决

形容注入信息的类 DependencyDescriptor

public class DependencyDescriptor extends InjectionPoint implements Serializable {
  // 被注入的申明类
    private final Class<?> declaringClass;
  // 办法注入的办法名
    @Nullable
    private String methodName;
  // 对应的参数
    @Nullable
    private Class<?>[] parameterTypes;
  // 参数索引
    private int parameterIndex;
  // 如果所包装的是成员属性,则这里记录该成员属性的名称
    @Nullable
    private String fieldName;
  // 是否必要依赖
    private final boolean required;
  // 是否是懒加载
    private final boolean eager;
  // 嵌套级别
    private int nestingLevel = 1;
  // 通常和 declaringClass 一样
    @Nullable
    private Class<?> containingClass;
  // 泛型解决
    @Nullable  
    private transient volatile ResolvableType resolvableType;
  // 依赖 TypeDescriptor 的缓存
    @Nullable
    private transient volatile TypeDescriptor typeDescriptor;
}

resolveDependency 办法

@Override
@Nullable
    public Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName,
            @Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {descriptor.initParameterNameDiscovery(getParameterNameDiscoverer());
        if (Optional.class == descriptor.getDependencyType()) {
      // 如:@Autowired private Optional<Rumenz> rumenzOpt;
            return createOptionalDependency(descriptor, requestingBeanName);
        }
        else if (ObjectFactory.class == descriptor.getDependencyType() ||
                ObjectProvider.class == descriptor.getDependencyType()) {
        // 如:@Autowired private ObjectProvider<Rumenz> obj;
            return new DependencyObjectProvider(descriptor, requestingBeanName);
        }
        else if (javaxInjectProviderClass == descriptor.getDependencyType()) {
        // 如:@Inject private Rumenz rumenz;
            return new Jsr330Factory().createDependencyProvider(descriptor, requestingBeanName);
        }
        else {Object result = getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary(descriptor, requestingBeanName);
            if (result == null) {result = doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter);
            }
            return result;
        }
    }

doResolveDependency 真正的依赖注入


@Nullable
    public Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName,
            @Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor);
        try {Object shortcut = descriptor.resolveShortcut(this);
            if (shortcut != null) {return shortcut;}

            Class<?> type = descriptor.getDependencyType();
            Object value = getAutowireCandidateResolver().getSuggestedValue(descriptor);
            if (value != null) {if (value instanceof String) {String strVal = resolveEmbeddedValue((String) value);
                    BeanDefinition bd = (beanName != null && containsBean(beanName) ?
                            getMergedBeanDefinition(beanName) : null);
                    value = evaluateBeanDefinitionString(strVal, bd);
                }
                TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());
                try {return converter.convertIfNecessary(value, type, descriptor.getTypeDescriptor());
                }
                catch (UnsupportedOperationException ex) {
                    // A custom TypeConverter which does not support TypeDescriptor resolution...
                    return (descriptor.getField() != null ?
                            converter.convertIfNecessary(value, type, descriptor.getField()) :
                            converter.convertIfNecessary(value, type, descriptor.getMethodParameter()));
                }
            }
      // 注入的是一组 Bean Array,List,Map 
            Object multipleBeans = resolveMultipleBeans(descriptor, beanName, autowiredBeanNames, typeConverter);
            if (multipleBeans != null) {return multipleBeans;}
      // 依据类型查找相应的 Bean
            Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor);
            if (matchingBeans.isEmpty()) {if (isRequired(descriptor)) {raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);
                }
                return null;
            }

            String autowiredBeanName;
            Object instanceCandidate;
      // 如果 Bean 的个数大于 1
            if (matchingBeans.size() > 1) {
        // 抉择 primary 的 Bean autowiredBeanName 就是查找到须要注入的 Bean
                autowiredBeanName = determineAutowireCandidate(matchingBeans, descriptor);
                if (autowiredBeanName == null) {if (isRequired(descriptor) || !indicatesMultipleBeans(type)) {return descriptor.resolveNotUnique(descriptor.getResolvableType(), matchingBeans);
                    }
                    else {
                        // In case of an optional Collection/Map, silently ignore a non-unique case:
                        // possibly it was meant to be an empty collection of multiple regular beans
                        // (before 4.3 in particular when we didn't even look for collection beans).
                        return null;
                    }
                }
                instanceCandidate = matchingBeans.get(autowiredBeanName);
            }
            else {
                // We have exactly one match.
                Map.Entry<String, Object> entry = matchingBeans.entrySet().iterator().next();
                autowiredBeanName = entry.getKey();
                instanceCandidate = entry.getValue();}

            if (autowiredBeanNames != null) {autowiredBeanNames.add(autowiredBeanName);
            }
            if (instanceCandidate instanceof Class) {instanceCandidate = descriptor.resolveCandidate(autowiredBeanName, type, this);
            }
            Object result = instanceCandidate;
            if (result instanceof NullBean) {if (isRequired(descriptor)) {raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);
                }
                result = null;
            }
            if (!ClassUtils.isAssignableValue(type, result)) {throw new BeanNotOfRequiredTypeException(autowiredBeanName, type, instanceCandidate.getClass());
            }
            return result;
        }
        finally {ConstructorResolver.setCurrentInjectionPoint(previousInjectionPoint);
        }
    }

原文: https://rumenz.com/rumenbiji/Spring-dependency-processing.html

正文完
 0