@AutoWire注释源码解析

[TOC]

spring的bean初始化会调用AbstractAutowireCapableBeanFactory.doCreateBean方法,在doCreateBean方法中会调用applyMergedBeanDefinitionPostProcessors,在applyMergedBeanDefinitionPostProcessors方法中调用了AutowiredAnnotationBeanPostProcessor.postProcessMergedBeanDefinition方法,他是@AutoWire的入口。

        synchronized (mbd.postProcessingLock) {
            if (!mbd.postProcessed) {
                try {
                    //入口
                    applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
                }
                catch (Throwable ex) {
                    throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                            "Post-processing of merged bean definition failed", ex);
                }
                mbd.postProcessed = true;
            }
        }
一,postProcessMergedBeanDefinition是@AutoWire入口方法
@Override
    public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class beanType, String beanName) {
        InjectionMetadata metadata = findAutowiringMetadata(beanName, beanType, null);
        metadata.checkConfigMembers(beanDefinition);
    }
二,进入到findAutowiringMetadata方法,双重检索
private InjectionMetadata findAutowiringMetadata(String beanName, Class clazz, @Nullable PropertyValues pvs) {
        // Fall back to class name as cache key, for backwards compatibility with custom callers.
        String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName());
        // 缓存中根据beanNmae获取该bean的InjectionMetadata
        InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey);
        //如果metadata为null或者metadata!=clazz
        if (InjectionMetadata.needsRefresh(metadata, clazz)) {
            synchronized (this.injectionMetadataCache) {
                metadata = this.injectionMetadataCache.get(cacheKey);
                //如果metadata为null或者metadata!=clazz
                if (InjectionMetadata.needsRefresh(metadata, clazz)) {
                    if (metadata != null) {
                        metadata.clear(pvs);
                    }
                    metadata = buildAutowiringMetadata(clazz);
                    //放入缓存
                    this.injectionMetadataCache.put(cacheKey, metadata);
                }
            }
        }
        return metadata;
    }
三,进入到buildAutowiringMetadata方法
private InjectionMetadata buildAutowiringMetadata(final Class clazz) {
        List elements = new ArrayList<>();
        Class targetClass = clazz;

        do {
            final List currElements = new ArrayList<>();
            //遍历这个类中的所有filed
            ReflectionUtils.doWithLocalFields(targetClass, field -> {
                //获取filed是否带了@AutoWire标签
                AnnotationAttributes ann = findAutowiredAnnotation(field);
                if (ann != null) {
                    //过滤掉static的filed
                    if (Modifier.isStatic(field.getModifiers())) {
                        if (logger.isWarnEnabled()) {
                            logger.warn("Autowired annotation is not supported on static fields: " + field);
                        }
                        return;
                    }
                    //这里就取了Autowired的一个required属性,这个属性的作用是
                    //如果这个是false就表明在自动装配的时候没有发现又对应的实例
                    //就跳过去,如果是true没有发现有与之匹配的就会抛出个异常,仅此而已
                    boolean required = determineRequiredStatus(ann);
                    currElements.add(new AutowiredFieldElement(field, required));
                }
            });
            //遍历这个类中的所有filedmethiod
            ReflectionUtils.doWithLocalMethods(targetClass, method -> {
                /**
                 * 这里获取一个桥接的方法对象
                 * 1,遍历class里面所有的method方法,findBridgedMethod方法会获取method方法的声明的类,
                 * 并且将该类下面所有的方法形成数组,然后遍历数组跟method比较,如果方法不同,但是方法的
                 * 名称和参数数量相同,则视为桥接方法返回
                 */
                Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
                //如果桥接方法和method不同,则直接返回
                if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {
                    return;
                }
                //获取method是否带了@AutoWire标签
                AnnotationAttributes ann = findAutowiredAnnotation(bridgedMethod);
                if (ann != null && method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
                //同样过滤静态方法
                    if (Modifier.isStatic(method.getModifiers())) {
                        if (logger.isWarnEnabled()) {
                            logger.warn("Autowired annotation is not supported on static methods: " + method);
                        }
                        return;
                    }
                    //参数数量0也过滤,注入set参数
                    if (method.getParameterCount() == 0) {
                        if (logger.isWarnEnabled()) {
                            logger.warn("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);
        //最后统一返回InjectionMetadata实例
        return new InjectionMetadata(clazz, elements);
    }

你可能感兴趣的:(@AutoWire注释源码解析)