Spring 源码解析四:Bean 的构造装载、属性值解析、注解扫描

x33g5p2x  于2022-02-11 发布在 Spring  
字(23.9k)|赞(0)|评价(0)|浏览(540)

上一篇主要介绍了 Bean 的注册、解析、实例化,但留下一些点待解析:

  • ConstructorResolver.autowireConstructor 如何进行构造装载并实例化的
  • CglibSubclassingInstantiationStrategy.instantiate 如何动态实例化 bean 的
  • BeanDefinitionValueResolver.resolveValueIfNecessary 如何解析属性值的
  • MergedAnnotations.from 如何扫描注解的

这一节,就来解析这几个点

1. ConstructorResolver.autowireConstructor

ConstructorResolver
的主要功能是在构造时载入依赖的 bean 和用 factory-method 实例化 bean,这里只讲第一个:在构造时载入依赖的 bean ConstructorResolver.autowireConstructor

class ConstructorResolver {
    public BeanWrapper autowireConstructor(String beanName, RootBeanDefinition mbd,
            @Nullable Constructor<?>[] chosenCtors, @Nullable Object[] explicitArgs) {
        // 实例化一个封装对象
        BeanWrapperImpl bw = new BeanWrapperImpl();

        // 需要使用的构造方法
        Constructor<?> constructorToUse = null;
        // 需要使用的构造参数
        Object[] argsToUse = null;

        // 如果指定了参数,就使用指定的参数
        if (explicitArgs != null) {
            argsToUse = explicitArgs;
        }
        else {
            Object[] argsToResolve = null;
            // 并发处理
            synchronized (mbd.constructorArgumentLock) {
                // 获取定义中已解析的构造方法
                constructorToUse = (Constructor<?>) mbd.resolvedConstructorOrFactoryMethod;
                if (constructorToUse != null && mbd.constructorArgumentsResolved) {
                    // 获取定义中已解析的参数,首先是resolvedConstructorArguments,其次是preparedConstructorArguments
                    argsToUse = mbd.resolvedConstructorArguments;
                    if (argsToUse == null) {
                        argsToResolve = mbd.preparedConstructorArguments;
                    }
                }
            }
            if (argsToResolve != null) {
                // 把参数解析成实际要用的数据,如bean装配、属性载入
                argsToUse = resolvePreparedArguments(beanName, mbd, bw, constructorToUse, argsToResolve);
            }
        }

        // 如果没有指定的构造方法或参数
        if (constructorToUse == null || argsToUse == null) {
            Constructor<?>[] candidates = chosenCtors;
            if (candidates == null) {
                // 如果传入的chosenCtors是空,则获取beanClass的构造方法
                Class<?> beanClass = mbd.getBeanClass();
                try {
                    candidates = (mbd.isNonPublicAccessAllowed() ?
                            beanClass.getDeclaredConstructors() : beanClass.getConstructors());
                }
                catch (Throwable ex) {
                    // ... 代码省略
                }
            }

            // 如果只有一个构造方法,并且没有指定explicitArgs和constructorArgumentValues
            if (candidates.length == 1 && explicitArgs == null && !mbd.hasConstructorArgumentValues()) {
                Constructor<?> uniqueCandidate = candidates[0];
                // 如果构造方法没有参数需要装配,直接实例化返回
                if (uniqueCandidate.getParameterCount() == 0) {
                    synchronized (mbd.constructorArgumentLock) {
                        mbd.resolvedConstructorOrFactoryMethod = uniqueCandidate;
                        mbd.constructorArgumentsResolved = true;
                        mbd.resolvedConstructorArguments = EMPTY_ARGS;
                    }
                    // 实例化bean
                    bw.setBeanInstance(instantiate(beanName, mbd, uniqueCandidate, EMPTY_ARGS));
                    return bw;
                }
            }

            // 有构造方法,且构造模式为AUTOWIRE_CONSTRUCTOR,则需要自动装配bean
            boolean autowiring = (chosenCtors != null ||
                    mbd.getResolvedAutowireMode() == AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR);
            ConstructorArgumentValues resolvedValues = null;

            // ... 代码省略


            // 选择一个参数数量、参数类型、参数顺序与需要实例化参数对象最接近的一个构造方法
            // 这里的计算比较复杂,有兴趣的朋友可以自行探索一下
            for (Constructor<?> candidate : candidates) {
                // ... 代码省略
            }

            // ... 代码省略
        }

        // 实例化bean
        bw.setBeanInstance(instantiate(beanName, mbd, constructorToUse, argsToUse));
        return bw;
    }

    // 实例化bean,默认使用CglibSubclassingInstantiationStrategy.instantiate来实例化
    private Object instantiate(
            String beanName, RootBeanDefinition mbd, Constructor<?> constructorToUse, Object[] argsToUse) {

        try {
            InstantiationStrategy strategy = this.beanFactory.getInstantiationStrategy();
            if (System.getSecurityManager() != null) {
                return AccessController.doPrivileged((PrivilegedAction<Object>) () ->
                        strategy.instantiate(mbd, beanName, this.beanFactory, constructorToUse, argsToUse),
                        this.beanFactory.getAccessControlContext());
            }
            else {
                return strategy.instantiate(mbd, beanName, this.beanFactory, constructorToUse, argsToUse);
            }
        }
        catch (Throwable ex) {
            // ... 代码省略
        }
    }
}

最终的实例化仍然需要CglibSubclassingInstantiationStrategy.instantiate来实现

2. CglibSubclassingInstantiationStrategy.instantiate

CglibSubclassingInstantiationStrategy
的主要功能是使用 cglib 的方式实例化 bean

public class CglibSubclassingInstantiationStrategy extends SimpleInstantiationStrategy {}

我们先来看看 SimpleInstantiationStrategy

public class SimpleInstantiationStrategy implements InstantiationStrategy {
    // 用于调用factory-method
    private static final ThreadLocal<Method> currentlyInvokedFactoryMethod = new ThreadLocal<>();

    @Override
    public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
        // 没有方法需要重载
        if (!bd.hasMethodOverrides()) {
            Constructor<?> constructorToUse;
            synchronized (bd.constructorArgumentLock) {
                // 首先获取已解析的构造方法
                constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
                if (constructorToUse == null) {
                    // 没有已解析的构造方法,则用beanClass获取
                    final Class<?> clazz = bd.getBeanClass();
                    // 接口不能实例化
                    if (clazz.isInterface()) {
                        throw new BeanInstantiationException(clazz, "Specified class is an interface");
                    }
                    try {
                        if (System.getSecurityManager() != null) {
                            constructorToUse = AccessController.doPrivileged(
                                    (PrivilegedExceptionAction<Constructor<?>>) clazz::getDeclaredConstructor);
                        }
                        else {
                            // 通过Class获取构造方法
                            constructorToUse = clazz.getDeclaredConstructor();
                        }
                        // 设为已解析的构造方法
                        bd.resolvedConstructorOrFactoryMethod = constructorToUse;
                    }
                    catch (Throwable ex) {
                        // 如果Class没有构造方法,报错
                    }
                }
            }
            // 调用Constructor..newInstance实例化
            return BeanUtils.instantiateClass(constructorToUse);
        }
        else {
            // 有方法需要重载,则需要用cglib生成一个新的子类
            return instantiateWithMethodInjection(bd, beanName, owner);
        }
    }

    // 方法注入实例化,留给子类实现
    protected Object instantiateWithMethodInjection(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
        throw new UnsupportedOperationException("Method Injection not supported in SimpleInstantiationStrategy");
    }

    @Override
    public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner,
            final Constructor<?> ctor, Object... args) {
        // 没有方法需要重载
        if (!bd.hasMethodOverrides()) {
            // ... 代码省略

            // 调用Constructor.newInstance实例化
            return BeanUtils.instantiateClass(ctor, args);
        }
        else {
            // 有方法需要重载,则需要用cglib生成一个新的子类
            return instantiateWithMethodInjection(bd, beanName, owner, ctor, args);
        }
    }

    // 方法注入实例化,留给子类实现
    protected Object instantiateWithMethodInjection(RootBeanDefinition bd, @Nullable String beanName,
            BeanFactory owner, @Nullable Constructor<?> ctor, Object... args) {
        throw new UnsupportedOperationException("Method Injection not supported in SimpleInstantiationStrategy");
    }

    // 通过factory-method初始化
    @Override
    public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner,
            @Nullable Object factoryBean, final Method factoryMethod, Object... args) {

        try {
            // ... 代码省略

            // 直接调用Method.invoke实例化
            Object result = factoryMethod.invoke(factoryBean, args);
            // 如果为null,实例化一个NullBean
            if (result == null) {
                result = new NullBean();
            }
            return result;
        }
        catch (IllegalArgumentException ex) {
            // ... 代码省略
        }
        catch (IllegalAccessException ex) {
            // ... 代码省略
        }
        catch (InvocationTargetException ex) {
            // ... 代码省略
        }
    }
}

我们先来看看 CglibSubclassingInstantiationStrategy

public class CglibSubclassingInstantiationStrategy extends SimpleInstantiationStrategy {
    @Override
    protected Object instantiateWithMethodInjection(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
        return instantiateWithMethodInjection(bd, beanName, owner, null);
    }

    @Override
    protected Object instantiateWithMethodInjection(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner,
            @Nullable Constructor<?> ctor, Object... args) {
        // 生成一个CglibSubclassCreator来实例化
        return new CglibSubclassCreator(bd, owner).instantiate(ctor, args);
    }
}

CglibSubclassCreatorCglibSubclassingInstantiationStrategy的内部类

private static class CglibSubclassCreator {
    // 实例化一个构造函数
    public Object instantiate(@Nullable Constructor<?> ctor, Object... args) {
        // 使用cglib Enhancer创建一个加强子类
        Class<?> subclass = createEnhancedSubclass(this.beanDefinition);
        Object instance;
        if (ctor == null) {
            // 如果没有指定构造函数,调用Constructor.newInstance实例化
            instance = BeanUtils.instantiateClass(subclass);
        }
        else {
            try {
                // 获取与ctor参数匹配的子类构造函数,再调用Constructor.newInstance实例化
                Constructor<?> enhancedSubclassConstructor = subclass.getConstructor(ctor.getParameterTypes());
                instance = enhancedSubclassConstructor.newInstance(args);
            }
            catch (Exception ex) {
                // ... 代码省略
            }
        }

        // ... 代码省略

        return instance;
    }

    // 使用cglib Enhancer创建一个加强子类
    private Class<?> createEnhancedSubclass(RootBeanDefinition beanDefinition) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(beanDefinition.getBeanClass());
        enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
        if (this.owner instanceof ConfigurableBeanFactory) {
            ClassLoader cl = ((ConfigurableBeanFactory) this.owner).getBeanClassLoader();
            enhancer.setStrategy(new ClassLoaderAwareGeneratorStrategy(cl));
        }
        enhancer.setCallbackFilter(new MethodOverrideCallbackFilter(beanDefinition));
        enhancer.setCallbackTypes(CALLBACK_TYPES);
        return enhancer.createClass();
    }
}

3. BeanDefinitionValueResolver.resolveValueIfNecessary

BeanDefinitionValueResolver
的主要功能是将配置的属性值装载到 bean 中

class BeanDefinitionValueResolver {
    public Object resolveValueIfNecessary(Object argName, @Nullable Object value) {
        // 在运行时对其他bean的引用
        if (value instanceof RuntimeBeanReference) {
            RuntimeBeanReference ref = (RuntimeBeanReference) value;
            // 解析引用bean
            return resolveReference(argName, ref);
        }
        // 在运行时对其他bean name的引用
        else if (value instanceof RuntimeBeanNameReference) {
            String refName = ((RuntimeBeanNameReference) value).getBeanName();
            // 使用doEvaluate解析bean名字,执行SpEL表达式
            refName = String.valueOf(doEvaluate(refName));
            if (!this.beanFactory.containsBean(refName)) {
                // 没注册过bean name,报错
            }
            return refName;
        }
        // 包含别名的bean定义
        else if (value instanceof BeanDefinitionHolder) {
            BeanDefinitionHolder bdHolder = (BeanDefinitionHolder) value;
            // 解析内部bean
            return resolveInnerBean(argName, bdHolder.getBeanName(), bdHolder.getBeanDefinition());
        }
        // bean定义
        else if (value instanceof BeanDefinition) {
            BeanDefinition bd = (BeanDefinition) value;
            // 内部bean名字
            String innerBeanName = "(inner bean)" + BeanFactoryUtils.GENERATED_BEAN_NAME_SEPARATOR +
                    ObjectUtils.getIdentityHexString(bd);
            // 解析内部bean
            return resolveInnerBean(argName, innerBeanName, bd);
        }
        // 注入依赖描述(类、方法、属性)
        else if (value instanceof DependencyDescriptor) {
            Set<String> autowiredBeanNames = new LinkedHashSet<>(4);
            // 解析依赖
            Object result = this.beanFactory.resolveDependency(
                    (DependencyDescriptor) value, this.beanName, autowiredBeanNames, this.typeConverter);
            for (String autowiredBeanName : autowiredBeanNames) {
                if (this.beanFactory.containsBean(autowiredBeanName)) {
                    // 注册依赖
                    this.beanFactory.registerDependentBean(autowiredBeanName, this.beanName);
                }
            }
            return result;
        }

        // ... 代码省略

        // 是字符类型的值
        else if (value instanceof TypedStringValue) {
            TypedStringValue typedStringValue = (TypedStringValue) value;
            // 使用evaluate解析bean名字,执行SpEL表达式
            Object valueObject = evaluate(typedStringValue);
            try {
                // 解析类型
                Class<?> resolvedTargetType = resolveTargetType(typedStringValue);
                // 如果有类型,把valueObject转换成这个类型
                if (resolvedTargetType != null) {
                    return this.typeConverter.convertIfNecessary(valueObject, resolvedTargetType);
                }
                // 没有指定类型,则返回原本的
                else {
                    return valueObject;
                }
            }
            catch (Throwable ex) {
                // ... 代码省略
            }
        }
        // 如果是NullBean,返回null
        else if (value instanceof NullBean) {
            return null;
        }
        // 默认当成SpEL表达式解析了
        else {
            return evaluate(value);
        }
    }
}

BeanDefinitionValueResolver.resolveReference
解析引用 bean

class BeanDefinitionValueResolver {
    private Object resolveReference(Object argName, RuntimeBeanReference ref) {
        try {
            Object bean;
            // 获取bean类型
            Class<?> beanType = ref.getBeanType();
            if (ref.isToParent()) {
                // 指明从父BeanFactory中获取
                BeanFactory parent = this.beanFactory.getParentBeanFactory();

                if (beanType != null) {
                    // 如果有beanType,直接通过类型获取bean
                    bean = parent.getBean(beanType);
                }
                else {
                    // 使用doEvaluate解析bean名字,执行SpEL表达式,然后根据名字查找bean
                    bean = parent.getBean(String.valueOf(doEvaluate(ref.getBeanName())));
                }
            }
            else {
                String resolvedName;
                if (beanType != null) {
                    // 如果有beanType,直接通过类型获取bean
                    NamedBeanHolder<?> namedBean = this.beanFactory.resolveNamedBean(beanType);
                    bean = namedBean.getBeanInstance();
                    resolvedName = namedBean.getBeanName();
                }
                else {
                    // 使用doEvaluate解析bean名字,执行SpEL表达式,然后根据名字查找bean
                    resolvedName = String.valueOf(doEvaluate(ref.getBeanName()));
                    bean = this.beanFactory.getBean(resolvedName);
                }
                // 注册依赖
                this.beanFactory.registerDependentBean(resolvedName, this.beanName);
            }
            // 如果是NullBean,返回null
            if (bean instanceof NullBean) {
                bean = null;
            }
            return bean;
        }
        catch (BeansException ex) {
            // ... 代码省略
        }
    }

    // 调用beanFactory来解析bean名字,执行SpEL表达式
    private Object doEvaluate(String value) {
        return this.beanFactory.evaluateBeanDefinitionString(value, this.beanDefinition);
    }
}

BeanDefinitionValueResolver.resolveInnerBean
解析内部 bean

class BeanDefinitionValueResolver {
    private Object resolveInnerBean(Object argName, String innerBeanName, BeanDefinition innerBd) {
        RootBeanDefinition mbd = null;
        try {
            // 获取合并父bean定义的bean定义
            mbd = this.beanFactory.getMergedBeanDefinition(innerBeanName, innerBd, this.beanDefinition);

            String actualInnerBeanName = innerBeanName;
            if (mbd.isSingleton()) {
                // 如果同类型的bean被实例化多次,则使用后缀#1,#2...来命名之后的bean
                actualInnerBeanName = adaptInnerBeanName(innerBeanName);
            }
            // 把新生成的名字注册到beanFactory
            this.beanFactory.registerContainedBean(actualInnerBeanName, this.beanName);
            // 获取依赖
            String[] dependsOn = mbd.getDependsOn();
            if (dependsOn != null) {
                for (String dependsOnBean : dependsOn) {
                    // 注册依赖
                    this.beanFactory.registerDependentBean(dependsOnBean, actualInnerBeanName);
                    // 确保加载
                    this.beanFactory.getBean(dependsOnBean);
                }
            }
            // 创建bean
            Object innerBean = this.beanFactory.createBean(actualInnerBeanName, mbd, null);
            // 如果bean实例是FactoryBean,则调用factory-method获取真正的bean
            if (innerBean instanceof FactoryBean) {
                boolean synthetic = mbd.isSynthetic();
                innerBean = this.beanFactory.getObjectFromFactoryBean(
                        (FactoryBean<?>) innerBean, actualInnerBeanName, !synthetic);
            }
            // 如果是NullBean,返回null
            if (innerBean instanceof NullBean) {
                innerBean = null;
            }
            return innerBean;
        }
        catch (BeansException ex) {
            // ... 代码省略
        }
    }

    // 如果同类型的bean被实例化多次,则使用后缀#1,#2...来命名之后的bean
    private String adaptInnerBeanName(String innerBeanName) {
        String actualInnerBeanName = innerBeanName;
        int counter = 0;
        String prefix = innerBeanName + BeanFactoryUtils.GENERATED_BEAN_NAME_SEPARATOR;
        while (this.beanFactory.isBeanNameInUse(actualInnerBeanName)) {
            counter++;
            actualInnerBeanName = prefix + counter;
        }
        return actualInnerBeanName;
    }
}

4. MergedAnnotations.from

MergedAnnotations.from
的底层实现其实是 TypeMappedAnnotations.from

TypeMappedAnnotations的主要功能就是搜索、操作注解

final class TypeMappedAnnotations implements MergedAnnotations {
    static MergedAnnotations from(AnnotatedElement element, SearchStrategy searchStrategy,
            RepeatableContainers repeatableContainers, AnnotationFilter annotationFilter) {
        // 没有可用的注解,直接返回NONE
        if (AnnotationsScanner.isKnownEmpty(element, searchStrategy)) {
            return NONE;
        }
        return new TypeMappedAnnotations(element, searchStrategy, repeatableContainers, annotationFilter);
    }

    static MergedAnnotations from(@Nullable Object source, Annotation[] annotations,
            RepeatableContainers repeatableContainers, AnnotationFilter annotationFilter) {
        // 没有要查找的注解,直接返回NONE
        if (annotations.length == 0) {
            return NONE;
        }
        return new TypeMappedAnnotations(source, annotations, repeatableContainers, annotationFilter);
    }
}
final class TypeMappedAnnotations implements MergedAnnotations {
    // 检查是否有annotationType
    @Override
    public <A extends Annotation> boolean isPresent(Class<A> annotationType) {
        // 过滤器没通过,返回false
        if (this.annotationFilter.matches(annotationType)) {
            return false;
        }
        // 扫描目标元素(类、方法、属性)
        return Boolean.TRUE.equals(scan(annotationType,
                IsPresent.get(this.repeatableContainers, this.annotationFilter, false)));
    }

    // 检查是否有annotationType
    @Override
    public boolean isPresent(String annotationType) {
        // 过滤器没通过,返回false
        if (this.annotationFilter.matches(annotationType)) {
            return false;
        }
        // 扫描目标元素(类、方法、属性)
        return Boolean.TRUE.equals(scan(annotationType,
                IsPresent.get(this.repeatableContainers, this.annotationFilter, false)));
    }

    // 获取目标元素的annotationType注解对象
    @Override
    public <A extends Annotation> MergedAnnotation<A> get(Class<A> annotationType,
            @Nullable Predicate<? super MergedAnnotation<A>> predicate,
            @Nullable MergedAnnotationSelector<A> selector) {
        // 过滤器没通过,返回空
        if (this.annotationFilter.matches(annotationType)) {
            return MergedAnnotation.missing();
        }
        // 扫描目标元素(类、方法、属性)
        MergedAnnotation<A> result = scan(annotationType,
                new MergedAnnotationFinder<>(annotationType, predicate, selector));
        return (result != null ? result : MergedAnnotation.missing());
    }

    // 获取目标元素的annotationType注解对象
    @Override
    public <A extends Annotation> MergedAnnotation<A> get(String annotationType,
            @Nullable Predicate<? super MergedAnnotation<A>> predicate,
            @Nullable MergedAnnotationSelector<A> selector) {
        // 过滤器没通过,返回空
        if (this.annotationFilter.matches(annotationType)) {
            return MergedAnnotation.missing();
        }
        // 扫描目标元素(类、方法、属性)
        MergedAnnotation<A> result = scan(annotationType,
                new MergedAnnotationFinder<>(annotationType, predicate, selector));
        return (result != null ? result : MergedAnnotation.missing());
    }

    // 扫描目标元素(类、方法、属性)
    private <C, R> R scan(C criteria, AnnotationsProcessor<C, R> processor) {
        // 如果有传入的注解对象,就不扫描目标元素了
        if (this.annotations != null) {
            R result = processor.doWithAnnotations(criteria, 0, this.source, this.annotations);
            return processor.finish(result);
        }
        // 有目标元素和扫描策略,扫描目标元素
        if (this.element != null && this.searchStrategy != null) {
            return AnnotationsScanner.scan(criteria, this.element, this.searchStrategy, processor);
        }
        return null;
    }
}

TypeMappedAnnotations.scan 的底层实现是 AnnotationsScanner.scan

abstract class AnnotationsScanner {
    // 扫描注解
    static <C, R> R scan(C context, AnnotatedElement source, SearchStrategy searchStrategy,
            AnnotationsProcessor<C, R> processor) {
        // 实际扫描处理
        R result = process(context, source, searchStrategy, processor);
        return processor.finish(result);
    }

    // 实际扫描处理
    private static <C, R> R process(C context, AnnotatedElement source,
            SearchStrategy searchStrategy, AnnotationsProcessor<C, R> processor) {
        // 如果目标元素是类,按类处理
        if (source instanceof Class) {
            return processClass(context, (Class<?>) source, searchStrategy, processor);
        }
        // 如果目标元素是方法,按方法处理
        if (source instanceof Method) {
            return processMethod(context, (Method) source, searchStrategy, processor);
        }
        // 不然按普通处理
        return processElement(context, source, processor);
    }
}

4.1. 按类处理

abstract class AnnotationsScanner {
    private static <C, R> R processClass(C context, Class<?> source,
            SearchStrategy searchStrategy, AnnotationsProcessor<C, R> processor) {

        switch (searchStrategy) {
            // 只搜索自身的注解,按普通处理
            case DIRECT:
                return processElement(context, source, processor);
            // 搜索自身与标记为@Inherited父类的注解
            case INHERITED_ANNOTATIONS:
                return processClassInheritedAnnotations(context, source, searchStrategy, processor);
            // 搜索自身与父类的注解
            case SUPERCLASS:
                return processClassHierarchy(context, source, processor, false, false);
            // 搜索自身、父类、接口的注解
            case TYPE_HIERARCHY:
                return processClassHierarchy(context, source, processor, true, false);
            // 搜索自身、父类、接口、getEnclosingClass()的注解
            case TYPE_HIERARCHY_AND_ENCLOSING_CLASSES:
                return processClassHierarchy(context, source, processor, true, true);
        }
        throw new IllegalStateException("Unsupported search strategy " + searchStrategy);
    }

    // 搜索自身与标记为@Inherited父类的注解
    private static <C, R> R processClassInheritedAnnotations(C context, Class<?> source,
            SearchStrategy searchStrategy, AnnotationsProcessor<C, R> processor) {
        try {
            // 如果除了自身以外,没有父类、接口、getEnclosingClass()的注解,按普通处理
            if (isWithoutHierarchy(source, searchStrategy)) {
                return processElement(context, source, processor);
            }
            Annotation[] relevant = null;
            int remaining = Integer.MAX_VALUE;
            int aggregateIndex = 0;
            Class<?> root = source;

            // source对象还可以继续向父类上溯
            // 非Object,非Ordered,非"java."开头
            while (source != null && source != Object.class && remaining > 0 &&
                    !hasPlainJavaAnnotationsOnly(source)) {

                // 聚合处理,如果有了,直接返回(默认未实现)
                R result = processor.doWithAggregate(context, aggregateIndex);
                if (result != null) {
                    return result;
                }

                // 获取所有public的注解
                Annotation[] declaredAnnotations = getDeclaredAnnotations(source, true);

                // ... 代码省略

                // 处理器自定义处理
                result = processor.doWithAnnotations(context, aggregateIndex, source, declaredAnnotations);
                // 如果有了,返回
                if (result != null) {
                    return result;
                }
                // 上溯父类,继续扫描
                source = source.getSuperclass();
                aggregateIndex++;
            }
        }
        catch (Throwable ex) {
            // ... 代码省略
        }
        return null;
    }

    // 搜索自身、父类、接口、getEnclosingClass()的注解
    private static <C, R> R processClassHierarchy(C context, int[] aggregateIndex, Class<?> source,
            AnnotationsProcessor<C, R> processor, boolean includeInterfaces, boolean includeEnclosing) {
        try {
            // 聚合处理,如果有了,直接返回(默认未实现)
            R result = processor.doWithAggregate(context, aggregateIndex[0]);
            if (result != null) {
                return result;
            }
            // 如果是Ordered或"java."开头,返回
            if (hasPlainJavaAnnotationsOnly(source)) {
                return null;
            }
            // 获取所有public的注解
            Annotation[] annotations = getDeclaredAnnotations(source, false);
            // 处理器自定义处理
            result = processor.doWithAnnotations(context, aggregateIndex[0], source, annotations);
            // 如果有了,返回
            if (result != null) {
                return result;
            }
            aggregateIndex[0]++;

            // 如果包括接口,继续搜索接口的
            if (includeInterfaces) {
                for (Class<?> interfaceType : source.getInterfaces()) {
                    R interfacesResult = processClassHierarchy(context, aggregateIndex,
                        interfaceType, processor, true, includeEnclosing);
                    if (interfacesResult != null) {
                        return interfacesResult;
                    }
                }
            }

            // 如果有父类,继续搜索父类的
            Class<?> superclass = source.getSuperclass();
            if (superclass != Object.class && superclass != null) {
                R superclassResult = processClassHierarchy(context, aggregateIndex,
                    superclass, processor, includeInterfaces, includeEnclosing);
                if (superclassResult != null) {
                    return superclassResult;
                }
            }

            // 如果包括getEnclosingClass(),继续搜索getEnclosingClass()的
            if (includeEnclosing) {
                try {
                    Class<?> enclosingClass = source.getEnclosingClass();
                    if (enclosingClass != null) {
                        R enclosingResult = processClassHierarchy(context, aggregateIndex,
                            enclosingClass, processor, includeInterfaces, true);
                        if (enclosingResult != null) {
                            return enclosingResult;
                        }
                    }
                }
                catch (Throwable ex) {
                    // ... 代码省略
                }
            }
        }
        catch (Throwable ex) {
            // ... 代码省略
        }
        return null;
    }
}

4.2. 按方法处理

abstract class AnnotationsScanner {
    private static <C, R> R processMethod(C context, Method source,
            SearchStrategy searchStrategy, AnnotationsProcessor<C, R> processor) {

        switch (searchStrategy) {
            // 只搜索自身的注解
            case DIRECT:
            // 搜索自身与标记为@Inherited父类的注解
            case INHERITED_ANNOTATIONS:
                return processMethodInheritedAnnotations(context, source, processor);
            // 搜索自身与父类的注解
            case SUPERCLASS:
                return processMethodHierarchy(context, new int[] {0}, source.getDeclaringClass(),
                        processor, source, false);
            // 搜索自身、父类、接口的注解
            case TYPE_HIERARCHY:
            // 搜索自身、父类、接口、getEnclosingClass()的注解
            case TYPE_HIERARCHY_AND_ENCLOSING_CLASSES:
                return processMethodHierarchy(context, new int[] {0}, source.getDeclaringClass(),
                        processor, source, true);
        }
        throw new IllegalStateException("Unsupported search strategy " + searchStrategy);
    }

    // 搜索自身与标记为@Inherited父类的注解
    private static <C, R> R processMethodInheritedAnnotations(C context, Method source,
            AnnotationsProcessor<C, R> processor) {

        try {
            // 聚合处理,如果有了,直接返回(默认未实现)
            // 不然,用processMethodAnnotations处理
            R result = processor.doWithAggregate(context, 0);
            return (result != null ? result :
                processMethodAnnotations(context, 0, source, processor));
        }
        catch (Throwable ex) {
            // ... 代码省略
        }
        return null;
    }

    // 处理方法的注解
    private static <C, R> R processMethodAnnotations(C context, int aggregateIndex, Method source,
            AnnotationsProcessor<C, R> processor) {

      // 获取所有public的注解
        Annotation[] annotations = getDeclaredAnnotations(source, false);
        // 处理器自定义处理
        R result = processor.doWithAnnotations(context, aggregateIndex, source, annotations);
        // 如果有了,返回
        if (result != null) {
            return result;
        }

        // ... 代码省略,桥接方法的处理

        return null;
    }

    // 搜索自身、父类、接口、getEnclosingClass()的注解
    private static <C, R> R processMethodHierarchy(C context, int[] aggregateIndex,
            Class<?> sourceClass, AnnotationsProcessor<C, R> processor, Method rootMethod,
            boolean includeInterfaces) {
        try {
            // 聚合处理,如果有了,直接返回(默认未实现)
            R result = processor.doWithAggregate(context, aggregateIndex[0]);
            if (result != null) {
                return result;
            }
            // 如果是Ordered或"java."开头,返回
            if (hasPlainJavaAnnotationsOnly(sourceClass)) {
                return null;
            }

            boolean calledProcessor = false;
            // 如果rootMethod是sourceClass的,直接处理
            if (sourceClass == rootMethod.getDeclaringClass()) {
                result = processMethodAnnotations(context, aggregateIndex[0],
                    rootMethod, processor);
                calledProcessor = true;
                if (result != null) {
                    return result;
                }
            }
            else {
                // 获取sourceClass的public方法
                for (Method candidateMethod : getBaseTypeMethods(context, sourceClass)) {
                    // 如果方法不是private,并且参数与rootMethod一直,直接处理
                    if (candidateMethod != null && isOverride(rootMethod, candidateMethod)) {
                        result = processMethodAnnotations(context, aggregateIndex[0],
                            candidateMethod, processor);
                        calledProcessor = true;
                        if (result != null) {
                            return result;
                        }
                    }
                }
            }
            // 如果rootMethod是private,返回null
            if (Modifier.isPrivate(rootMethod.getModifiers())) {
                return null;
            }

            // 如果包括接口,继续搜索接口的
            if (includeInterfaces) {
                for (Class<?> interfaceType : sourceClass.getInterfaces()) {
                    R interfacesResult = processMethodHierarchy(context, aggregateIndex,
                        interfaceType, processor, rootMethod, true);
                    if (interfacesResult != null) {
                        return interfacesResult;
                    }
                }
            }

            // 如果有父类,继续搜索父类的
            Class<?> superclass = sourceClass.getSuperclass();
            if (superclass != Object.class && superclass != null) {
                R superclassResult = processMethodHierarchy(context, aggregateIndex,
                    superclass, processor, rootMethod, includeInterfaces);
                if (superclassResult != null) {
                    return superclassResult;
                }
            }
        }
        catch (Throwable ex) {
            // ... 代码省略
        }
        return null;
    }
}

4.3 按普通处理

abstract class AnnotationsScanner {
    private static <C, R> R processElement(C context, AnnotatedElement source,
            AnnotationsProcessor<C, R> processor) {

        try {
            // 聚合处理,如果有了,直接返回(默认未实现)
            // 不然,调用getDeclaredAnnotations获取注解来处理
            R result = processor.doWithAggregate(context, 0);
            return (result != null ? result : processor.doWithAnnotations(
                context, 0, source, getDeclaredAnnotations(source, false)));
        }
        catch (Throwable ex) {
            // ... 代码省略
        }
        return null;
    }
}

后续

更多博客,查看 https://github.com/senntyou/blogs

作者:深予之 (@senntyou)

版权声明:自由转载-非商用-非衍生-保持署名(创意共享 3.0 许可证

相关文章