Spring Boot 2 實踐記錄之 組合註解原理

Spring 的組合註解功能,網上有很多文章介紹,不過都是介紹其使用方法,鮮有其原理解析。

組合註解並非 Java 的原生能力。就是說,想通過用「註解A」來註解「註解B」,再用「註解B」 來註解 C(類或方法),就能夠使 C 同時擁有「註解A」和「註解B」是行不通的。

示例如下:

先定義註解 SuperAnno:

複製代碼

import java.lang.annotation.*;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface SuperAnno {
}

複製代碼

再定義註解 SubAnno,並使用 SuperAnno 註解 SubAnno:

複製代碼

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@SuperAnno
@SomeAnno
public @interface SubAnno {
}

複製代碼

定義 Test,使用 SubAnno 註解 Test:

@SubAnno
public class Test {

}

測試一下,看看我們能不能拿到 Test 的 SuperAnno 註解:

複製代碼

import java.lang.annotation.Annotation;

public class Main {

    public static void main(String[] args) {
    // write your code here
        Test test = new Test();
        Class<?> cl = test.getClass();
        Annotation[] annotations = cl.getAnnotations();
        for(Annotation annotation: annotations) {
            System.out.println(annotation.annotationType());
        }
    }
}

複製代碼

打印出來的結果爲:

interface com.company.SubAnno

唔,SuperAnno 沒有出現。

怎麼拿到合併的註解呢?

核心的思路就是拿到註解後,遞歸獲取其上的註解,見下例:

複製代碼

import javax.annotation.*;
import java.lang.annotation.*;
import java.util.ArrayList;

public class Main {

    private ArrayList<Annotation> annos = new ArrayList<>();

    public static void main(String[] args) {
    // write your code here
        Test test = new Test();
        Class<?> cl = test.getClass();
        Main main = new Main();
        main.getAnnos(cl);
        for(Annotation anno: main.annos) {
            System.out.println(anno.annotationType());
        }
    }

    private void getAnnos(Class<?> cl) {
        Annotation[] annotations = cl.getAnnotations();
        for(Annotation annotation: annotations) {
            if (annotation.annotationType() != Deprecated.class &&
                    annotation.annotationType() != SuppressWarnings.class &&
                    annotation.annotationType() != Override.class &&
                    annotation.annotationType() != PostConstruct.class &&
                    annotation.annotationType() != PreDestroy.class &&
                    annotation.annotationType() != Resource.class &&
                    annotation.annotationType() != Resources.class &&
                    annotation.annotationType() != Generated.class &&
                    annotation.annotationType() != Target.class &&
                    annotation.annotationType() != Retention.class &&
                    annotation.annotationType() != Documented.class &&
                    annotation.annotationType() != Inherited.class
            ) {
                annos.add(annotation);
                getAnnos(annotation.annotationType());
            }
        }
    }
}

複製代碼

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章