@Autowired和@Resource 解析

准备

1.通过前面部分的spring源码解析, 我们知道BeanPostProcessor, 会在普通bean实例化之前实例化并初始化完成!并在bean的整个实例化和初始化过程前后执行其加强的方法;
2.@Autowired和@Resource都是通过BeanPostProcessor进行处理的, 处理的时机是在bean实例化后, 属性注入时执行, 即AbstractAutowireCapableBeanFactory#populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw)方法中
3.@Autowired的实现是通过AutowiredAnnotationBeanPostProcessor后置处理器完成的

启动类

public class AutowireStarter {
    public static void main(String[] args) {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AutowireConfig.class);
    }
}

配置类

@Configuration
@ComponentScan("com.tca.spring.framework.learning.ioc.autowire")
public class AutowireConfig {
}

普通bean

@Component
public class A {
    @Autowired
    private B b;
}
@Component
public class B {
}

AbstractAutowireCapableBeanFactory#populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw)

/**
 * Populate the bean instance in the given BeanWrapper with the property values
 * from the bean definition.
 * 翻译: 注入bean的属性
 * @param beanName the name of the bean
 * @param mbd the bean definition for the bean
 * @param bw the BeanWrapper with bean instance
 */
@SuppressWarnings("deprecation")  // for postProcessPropertyValues
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
    // 1.这里跳过
    if (bw == null) {
        if (mbd.hasPropertyValues()) {
            throw new BeanCreationException(
                mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
        }
        else {
            // Skip property population phase for null instance.
            return;
        }
    }

    // Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
    // state of the bean before properties are set. This can be used, for example,
    // to support styles of field injection.
    // 翻译: 在注入属性之前, 可以使用BeanPostProcessor修改bean的状态, 用来支持字段注入的不同方式
    boolean continueWithPropertyPopulation = true;
	// 2.这里是第五次使用BeanPostProcessor, 这里使用的是InstantiationAwareBeanPostProcessor
    // 依次拿到所有的InstantiationAwareBeanPostProcessor, 并执行它们的postProcessAfterInstantiation()方法, 这个方法的作用是:判断当前bean对象是否需要在创建完成之后进行属性注入, 如果需要, 返回true, 不需要, 则返回false;
    // spring内置的三个InstantiationAwareBeanPostProcessor都是返回true
    // ImportAwareBeanPostProcessor:
    // CommonAnnotationBeanPostProcessor:
    // AutowiredAnnotationBeanPostProcessor:
    if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof InstantiationAwareBeanPostProcessor) {
                InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
                    continueWithPropertyPopulation = false;
                    break;
                }
            }
        }
    }
	// 3.根据上面InstantiationAwareBeanPostProcessor的执行结果, 只要有一个返回的结果为不需要注入属性, 那么这里会直接终止方法执行
    if (!continueWithPropertyPopulation) {
        return;
    }
	// 4.对于A, 这里会跳过
    PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
	// 5.对于A, 这里也会跳过mbd.getResolvedAutowireMode() == AUTOWIRE_NO, 没有使用自动注入
    if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME || mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) {
        MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
        // Add property values based on autowire by name if applicable.
        if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME) {
            autowireByName(beanName, mbd, bw, newPvs);
        }
        // Add property values based on autowire by type if applicable.
        if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) {
            autowireByType(beanName, mbd, bw, newPvs);
        }
        pvs = newPvs;
    }
    // 6.这里为true, 即第五次使用的BeanPostProcessor
    boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
    // 7.这里为false
    boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);

    PropertyDescriptor[] filteredPds = null;
    if (hasInstAwareBpps) {
        if (pvs == null) {
            pvs = mbd.getPropertyValues();
        }
        // 8.第六次使用BeanPostProcessor, 这次跟第五次使用的BeanPostProcessor一样,InstantiationAwareBeanPostProcessor,但是调用的方法不一样, 这一次调用的是postProcessProperties()方法
        // 【注意:】这里会完成属性注入 
        // ImportAwareBeanPostProcessor: 这个方法没有对普通bean作处理, 跳过
    	// CommonAnnotationBeanPostProcessor: 解析@Resource注解
    	// AutowiredAnnotationBeanPostProcessor: 解析@Autowired注解
        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;
            }
        }
    }
    // 9.对于A, 下面跳过
    if (needsDepCheck) {
        if (filteredPds == null) {
            filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
        }
        checkDependencies(beanName, mbd, filteredPds, pvs);
    }

    if (pvs != null) {
        applyPropertyValues(beanName, mbd, bw, pvs);
    }
}

问题解答:

1.如何让@Autowired, @Resource等注解同时失效, 即不能实现注入

自定义InstantiationAwareBeanPostProcessor接口实现类并注入到容器中,重写方法postProcessAfterInstantiation(),这个方法默认返回true,我们自定义的将其返回false即可【原理:第五次使用bpp时,会调用所有InstantiationAwareBeanPostProcessor的postProcessAfterInstantiation方法,判断是否需要属性注入】

@Component
public class CustomInstantiationAwareBeanPostProcessor implements InstantiationAwareBeanPostProcessor {

    @Override
    public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
        return false;
    }
}

1.@Autowired解析

1.1 AutowiredAnnotationBeanPostProcessor#postProcessProperties(PropertyValues pvs, Object bean, String beanName)

/**
 * 解析@Autowired的入口方法
 */
@Override
public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
    // 见@1.2
    InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs);
    try {
        // 见@1.3
        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;
}

1.2 AutowiredAnnotationBeanPostProcessor#findAutowiringMetadata(String beanName, Class<?> clazz, @Nullable PropertyValues pvs)

private InjectionMetadata findAutowiringMetadata(String beanName, Class<?> clazz, @Nullable PropertyValues pvs) {
    // Fall back to class name as cache key, for backwards compatibility with custom callers.
    // 1.获取beanName对应的cacheKey
    String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName());
    // 2.根据cacheKey从injectionMetadataCache缓存中获取对应的InjectionMetadata
    // 一般这里是可以直接获取到的, 即metadata不为null, 那么metadata是什么时候放到injectionMetadataCache缓存中的? -- 见下面的问题解答
    InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey);
    if (InjectionMetadata.needsRefresh(metadata, clazz)) {
        synchronized (this.injectionMetadataCache) {
            metadata = this.injectionMetadataCache.get(cacheKey);
            if (InjectionMetadata.needsRefresh(metadata, clazz)) {
                if (metadata != null) {
                    metadata.clear(pvs);
                }
                // 3.当没有取到metadata时, 会构建metadata, 见@1.3
                metadata = buildAutowiringMetadata(clazz);
                this.injectionMetadataCache.put(cacheKey, metadata);
            }
        }
    }
    return metadata;
}

问题解答:

1.普通bean的metadata是什么时候放入injectionMetadataCache缓存中的?

1.在AbstractAutowireCapableBeanFactory#doCreateBean()方法中, 我们在bean实例化, 调用
instanceWrapper = createBeanInstance(beanName, mbd, args); 方法之后, 会第三次使用BeanPostProcessor, 
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName); 在这个方法中, 会调用所有MergedBeanDefinitionPostProcessor对象的postProcessMergedBeanDefinition()方法;
2.我们内置的MergedBeanDefinitionPostProcessor有三个:
CommonAnnotationBeanPostProcessor
AutowiredAnnotationBeanPostProcessor
ApplicationListenerDetector
在 AutowiredAnnotationBeanPostProcessor执行postProcessMergedBeanDefinition()方法时, 会解析当前bean的字段, 封装成metadata放入缓存中, AutowiredAnnotationBeanPostProcessor#buildAutowiringMetadata(clazz)方法会创建metadata, 这里也说明了第三次使用BeanPostProcessor的作用

1.3 AutowiredAnnotationBeanPostProcessor#buildAutowiringMetadata(final Class<?> clazz)

private InjectionMetadata buildAutowiringMetadata(final Class<?> clazz) {
    List<InjectionMetadata.InjectedElement> elements = new ArrayList<>();
    Class<?> targetClass = clazz;

    do {
        final List<InjectionMetadata.InjectedElement> currElements = new ArrayList<>();

        ReflectionUtils.doWithLocalFields(targetClass, field -> {
            // 1.获取字段的@Autowired注解
            AnnotationAttributes ann = findAutowiredAnnotation(field);
            if (ann != null) {
                if (Modifier.isStatic(field.getModifiers())) {
                    if (logger.isInfoEnabled()) {
                        logger.info("Autowired annotation is not supported on static fields: " + field);
                    }
                    return;
                }
                // 2.@Autowired的required属性, 默认为true
                boolean required = determineRequiredStatus(ann);
                // 3.添加
                currElements.add(new AutowiredFieldElement(field, required));
            }
        });

        // 4.解析方法上的@Autowired属性, 暂略
        ReflectionUtils.doWithLocalMethods(targetClass, method -> {
            Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
            if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {
                return;
            }
            AnnotationAttributes ann = findAutowiredAnnotation(bridgedMethod);
            if (ann != null && method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
                if (Modifier.isStatic(method.getModifiers())) {
                    if (logger.isInfoEnabled()) {
                        logger.info("Autowired annotation is not supported on static methods: " + method);
                    }
                    return;
                }
                if (method.getParameterCount() == 0) {
                    if (logger.isInfoEnabled()) {
                        logger.info("Autowired annotation should only be used on methods with parameters: " + method);
                    }
                }
                boolean required = determineRequiredStatus(ann);
                PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
                currElements.add(new AutowiredMethodElement(method, required, pd));
            }
        });

        elements.addAll(0, currElements);
        targetClass = targetClass.getSuperclass();
    }
    while (targetClass != null && targetClass != Object.class);

    return new InjectionMetadata(clazz, elements);
}

1.4 InjectionMetadata#inject(Object target, @Nullable String beanName, @Nullable PropertyValues pvs)

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()) {
        for (InjectedElement element : elementsToIterate) {
            if (logger.isTraceEnabled()) {
                logger.trace("Processing injected element of bean '" + beanName + "': " + element);
            }
            // 元素注入, 见@1.5
            // target: a对应的bean, beanName: a, pvs: length==0
            element.inject(target, beanName, pvs);
        }
    }
}

1.5 AutowiredFieldElement#inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs)

protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
    // 上述bean是A对象, beanName为a
    // 1.注入的属性字段, 这里是b对应的field
    Field field = (Field) this.member;
    Object value;
    // 2.这里cached为false
    if (this.cached) {
        value = resolvedCachedArgument(beanName, this.cachedFieldValue);
    }
    else {
        // 3.创建DependencyDescriptor对象
        DependencyDescriptor desc = new DependencyDescriptor(field, this.required);
        desc.setContainingClass(bean.getClass());
        Set<String> autowiredBeanNames = new LinkedHashSet<>(1);
        Assert.state(beanFactory != null, "No BeanFactory available");
        // 4.这里的beanFactory==DefaultListableBeanFactory
        TypeConverter typeConverter = beanFactory.getTypeConverter();
        try {
            // 5.【很重要:从容器中获取需要注入的bean, 见@1.6】
            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;
            }
        }
    }
    // 6.找到bean之后, 使用反射注入 
    if (value != null) {
        ReflectionUtils.makeAccessible(field);
        field.set(bean, value);
    }
}

1.6 DefaultListableBeanFactory#resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName,

  @Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter)
@Override
@Nullable
public Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName,
                                @Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {
    // 1.跳过
    descriptor.initParameterNameDiscovery(getParameterNameDiscoverer());
    if (Optional.class == descriptor.getDependencyType()) {
        return createOptionalDependency(descriptor, requestingBeanName);
    }
    else if (ObjectFactory.class == descriptor.getDependencyType() ||
             ObjectProvider.class == descriptor.getDependencyType()) {
        return new DependencyObjectProvider(descriptor, requestingBeanName);
    }
    else if (javaxInjectProviderClass == descriptor.getDependencyType()) {
        return new Jsr330Factory().createDependencyProvider(descriptor, requestingBeanName);
    }
    else {
        // 2.这里一般返回null
        Object result = getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary(
            descriptor, requestingBeanName);
        if (result == null) {
            // 3.【重点:这里是获取注入的bean的核心方法, 见@1.7】
            // descriptor: b对应的descriptor, requestingBeanName: a, autowiredBeanNames:[], typeConverter: SimpleTypeConverter
            result = doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter);
        }
        return result;
    }
}

1.7 DefaultListableBeanFactory#doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName,

  @Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter)
@Nullable
public Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName,
                                  @Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {

    InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor);
    try {
        // 1.这里一般为null
        Object shortcut = descriptor.resolveShortcut(this);
        if (shortcut != null) {
            return shortcut;
        }
	    // 2.获取注入的类的Class对象, 这里为B
        Class<?> type = descriptor.getDependencyType();
        Object value = getAutowireCandidateResolver().getSuggestedValue(descriptor);
        // 3.这里一般为null, 跳过
        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()));
            }
        }
	    // 4.判断是否为stream、array、collection、map这些, 这里b不是, 所以为null
        Object multipleBeans = resolveMultipleBeans(descriptor, beanName, autowiredBeanNames, typeConverter);
        if (multipleBeans != null) {
            return multipleBeans;
        }
        // 5.根据注入对象的类型查询匹配到的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;
	    // 6.这里matchingBeans里只有一个("b", Class<B>)
        if (matchingBeans.size() > 1) {
            // 当有多个匹配类型的bean时, 此时根据name选择对应的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();
            // "b"
            autowiredBeanName = entry.getKey();
            // Class<B>
            instanceCandidate = entry.getValue();
        }

        if (autowiredBeanNames != null) {
            autowiredBeanNames.add(autowiredBeanName);
        }
        if (instanceCandidate instanceof Class) {
            // 根据"b"和Class<B>从容器中获取对应的bean, 这里会走之前的getBean的方法, 可能会出现循环依赖的问题
            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);
    }
}

1.8 DefaultListableBeanFactory#findAutowireCandidates(@Nullable String beanName, Class<?> requiredType, DependencyDescriptor descriptor)

protected Map<String, Object> findAutowireCandidates(
    @Nullable String beanName, Class<?> requiredType, DependencyDescriptor descriptor) {
	// 1.根据类型找到对应的bean的name, 这里找到的是b
    String[] candidateNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
        this, requiredType, true, descriptor.isEager());
    Map<String, Object> result = new LinkedHashMap<>(candidateNames.length);
    // 2.这里直接跳过, 因为resolvableDependencies.entrySet().getKey()分别是:
    // ApplicationContext、ResourceLoader、BeanFactory、ApplicationEventPublisher, 我们的requiredType是B
    for (Map.Entry<Class<?>, Object> classObjectEntry : this.resolvableDependencies.entrySet()) {
        Class<?> autowiringType = classObjectEntry.getKey();
        if (autowiringType.isAssignableFrom(requiredType)) {
            Object autowiringValue = classObjectEntry.getValue();
            autowiringValue = AutowireUtils.resolveAutowiringValue(autowiringValue, requiredType);
            if (requiredType.isInstance(autowiringValue)) {
                result.put(ObjectUtils.identityToString(autowiringValue), autowiringValue);
                break;
            }
        }
    }
    // 3.这里的candidateNames只有b
    for (String candidate : candidateNames) {
        // 判断是否是自引用(不是自引用), 确定指定的bean定义是否符合autowire候选者的条件(符合)
        if (!isSelfReference(beanName, candidate) && isAutowireCandidate(candidate, descriptor)) {
            // 进入, 将("b", Class<B>)存到result中
            addCandidateEntry(result, candidate, descriptor, requiredType);
        }
    }
    // 4.跳过
    if (result.isEmpty()) {
        boolean multiple = indicatesMultipleBeans(requiredType);
        // Consider fallback matches if the first pass failed to find anything...
        DependencyDescriptor fallbackDescriptor = descriptor.forFallbackMatch();
        for (String candidate : candidateNames) {
            if (!isSelfReference(beanName, candidate) && isAutowireCandidate(candidate, fallbackDescriptor) &&
                (!multiple || getAutowireCandidateResolver().hasQualifier(descriptor))) {
                addCandidateEntry(result, candidate, descriptor, requiredType);
            }
        }
        if (result.isEmpty() && !multiple) {
            // Consider self references as a final pass...
            // but in the case of a dependency collection, not the very same bean itself.
            for (String candidate : candidateNames) {
                if (isSelfReference(beanName, candidate) &&
                    (!(descriptor instanceof MultiElementDescriptor) || !beanName.equals(candidate)) &&
                    isAutowireCandidate(candidate, fallbackDescriptor)) {
                    addCandidateEntry(result, candidate, descriptor, requiredType);
                }
            }
        }
    }
    return result;
}