博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring Boot 2 实践记录之 组合注解原理
阅读量:4323 次
发布时间:2019-06-06

本文共 2801 字,大约阅读时间需要 9 分钟。

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@SomeAnnopublic @interface SubAnno {}

定义 Test,使用 SubAnno 注解 Test:

@SubAnnopublic 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
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()); } } }}

 

转载于:https://www.cnblogs.com/matchless/p/10388184.html

你可能感兴趣的文章
JPanel重绘
查看>>
图片放大器——wpf
查看>>
SCALA STEP BY STEP
查看>>
cocos2d-x学习笔记
查看>>
MySql中的变量定义
查看>>
Ruby数组的操作
查看>>
hdu1181暴搜
查看>>
解码字符串 Decode String
查看>>
json学习笔记
查看>>
工具:linux 性能监控工具-nmon
查看>>
fatal error C1853
查看>>
Ural 1001 - Reverse Root
查看>>
玩转webpack之webpack的entry output
查看>>
java 操作mongodb查询条件的常用设置
查看>>
黑马程序员_java基础笔记(02)...java语言基础组成
查看>>
对innodb 拷贝文件实现数据库的方式(转)
查看>>
python知识点 2014-07-09
查看>>
FloatingActionButton的一点学习感悟
查看>>
ABAP CDS ON HANA-(10)項目結合して一つ項目として表示
查看>>
网站地址信息
查看>>