天天看點

從Spring源碼中學習如何查找自定義注解

看幾個基礎的注解

@AliasFor

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface AliasFor {
    @AliasFor("attribute")
    String value() default "";

    @AliasFor("value")
    String attribute() default "";

    Class<? extends Annotation> annotation() default Annotation.class;
}      

AliasFor這個注解很奇怪,value的别名是attribute,attribute的别名是value

那麼它的行為在哪裡被定義的呢?在AnnotationTypeMapping中我們可以找到答案

// 這裡使用了AnnotationsScanner的getDeclaredAnnotation方法來擷取所有的AliasFor注解的方法
// AnnotationsScanner 是spring中的非公開抽象類,在我們的代碼中不能直接進行使用
// Spring中沒有提供子類
private Map<Method, List<Method>> resolveAliasedForTargets() {
    Map<Method, List<Method>> aliasedBy = new HashMap<>();
    for (int i = 0; i < this.attributes.size(); i++) {
        Method attribute = this.attributes.get(i);
        AliasFor aliasFor = AnnotationsScanner.getDeclaredAnnotation(attribute, AliasFor.class);
        if (aliasFor != null) {
            Method target = resolveAliasTarget(attribute, aliasFor);
            aliasedBy.computeIfAbsent(target, key -> new ArrayList<>()).add(attribute);
        }
    }
    return Collections.unmodifiableMap(aliasedBy);
}

// 為了簡潔,我将源代碼中其餘部分省略掉了,可以看到,這裡使用用反射得到的Method的getAnnotation方法得到執行個體
private Method resolveAliasTarget(Method attribute, AliasFor aliasFor, boolean checkAliasPair) {
    // ... ...
    Method target = AttributeMethods.forAnnotationType(targetAnnotation).get(targetAttributeName);
    // ... ...
    if (isAliasPair(target) && checkAliasPair) {
        AliasFor targetAliasFor = target.getAnnotation(AliasFor.class);
        if (targetAliasFor != null) {
            Method mirror = resolveAliasTarget(target, targetAliasFor, false);
            if (!mirror.equals(attribute)) {
                throw new AnnotationConfigurationException(String.format(
                    "%s must be declared as an @AliasFor %s, not %s.",
                    StringUtils.capitalize(AttributeMethods.describe(target)),
                    AttributeMethods.describe(attribute), AttributeMethods.describe(mirror)));
            }
        }
    }
    return target;
}      

通過學習@AliasFor,我們知道了可以通過先活動Method,再或得其修飾的注解的方法。

根據這樣的方法,我們可以使用下面的代碼,找到類DockingHandlers中所有被注解@DockIngMessage修飾的方法

// DockIngMessage 是自定義的注解
Method[] methods = DockingHandlers.class.getMethods();
for (Method method : methods) {
    DockIngMessage dockIngMessage = method.getAnnotation(DockIngMessage.class);
    if (dockIngMessage != null) {
        System.out.println(dockIngMessage.name());
    }
}      

@Bean

@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Bean {

    @AliasFor("name")
    String[] value() default {};

    @AliasFor("value")
    String[] name() default {};

    @Deprecated
    Autowire autowire() default Autowire.NO;

    boolean autowireCandidate() default true;
    String initMethod() default "";
    String destroyMethod() default AbstractBeanDefinition.INFER_METHOD;
}      

@Bean注解是Spring中用得比較廣泛的注解之一,來看看Spring源碼中是怎麼查找@Bean注解的

public static boolean isBeanAnnotated(Method method) {
    return AnnotatedElementUtils.hasAnnotation(method, Bean.class);
}      

使用了AnnotatedElementUtils工具類,那麼我們就可以把上面的代碼改造一下

Method[] methods = DockingHandlers.class.getMethods();
for (Method method : methods) {
    if (AnnotatedElementUtils.hasAnnotation(method, DockIngMessage.class)) {
        DockIngMessage dockIngMessage = AnnotatedElementUtils.getMergedAnnotation(method,DockIngMessage.class);
        System.out.println(dockIngMessage.name());
    }
}
// 相比于判斷 != null , 這樣的寫法相對優雅了許多      

至于Bean到底是怎麼生效的,我們需要留到以後研究Spring容器的時候再讨論

@Controller

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Controller {

    @AliasFor(annotation = Component.class)
    String value() default "";
}      

在Controller的test裡面有這麼一段代碼

@Test
public void testWithComponentAnnotationOnly() {
    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
    provider.addIncludeFilter(new AnnotationTypeFilter(Component.class));
    provider.addExcludeFilter(new AnnotationTypeFilter(Repository.class));
    provider.addExcludeFilter(new AnnotationTypeFilter(Service.class));
    provider.addExcludeFilter(new AnnotationTypeFilter(Controller.class));
    Set<BeanDefinition> candidates = provider.findCandidateComponents(TEST_BASE_PACKAGE);
    assertThat(candidates.size()).isEqualTo(3);
    assertThat(containsBeanClass(candidates, NamedComponent.class)).isTrue();
    assertThat(containsBeanClass(candidates, ServiceInvocationCounter.class)).isTrue();
    assertThat(containsBeanClass(candidates, BarComponent.class)).isTrue();
    assertThat(containsBeanClass(candidates, FooServiceImpl.class)).isFalse();
    assertThat(containsBeanClass(candidates, StubFooDao.class)).isFalse();
    assertThat(containsBeanClass(candidates, NamedStubDao.class)).isFalse();
}      

也就是說,可以利用掃包的方式來擷取某個包下被某個注解修飾的類。

總結

查找某注解修飾的所有類就使用 ClassPathScanningCandidateComponentProvider 進行掃描。

查找某注解修飾的方法,就先找到那個類,然後得到所有的方法,使用AnnotatedElementUtils.hasAnnotation判斷方法是否被某注解修飾即可

下面是一個簡單的例子

ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
provider.addIncludeFilter(new AnnotationTypeFilter(DockingAnnotation.class));
Set<BeanDefinition> candidates = provider.findCandidateComponents("package_name");
for (BeanDefinition definition : candidates){
    try {
        Class clz = Class.forName(definition.getBeanClassName());
        Method[] methods = clz.getMethods();
        for (Method method : methods){
            if (AnnotatedElementUtils.hasAnnotation(method,DockIngMessage.class)){
                DockIngMessage dockIngMessage = AnnotatedElementUtils.getMergedAnnotation(method,DockIngMessage.class);
                System.out.println(dockIngMessage.name());
            }
        }
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
}