java中自定义注解的应用

  要想深刻的理解注解,我们必须能实现自己的注解,然后应用自己的注解去实现特定的业务,使用注解可以更优雅的做到某些事情。

有这样一个场景,在需要文件导出时,我们需要将一个 model 中的一些重要字段导出到 csv 文件中去,当然还有一些没用的或者不能暴露的字段,不需要导出到文件中,这样业务如果一般实现起来我们可以将需要导出的字段写入一个配置文件,然后根据配置文件进行比对,需要导出的就写入到流中实现导出。但是这样做始终感觉扩展性不是很好,而且实现方式有点粗暴,于是想到了通过反射来做,为需要导出的字段加上自定义的注解,当该属性被注解时导出,我们来看看实现方式。

首先自定义注解:

1 @Retention(RetentionPolicy.RUNTIME)
2 @Target(ElementType.FIELD)
3 
4 //文件导出时,只导出带有改注解的字段
5 public @interface ExportFieldAnnotation {
6 
7 }

然后,在 model 中需要导出的字段上添加该注解:

 1 public class IndicatorModel {
 2     private String indexId;
 3     @ExportFieldAnnotation
 4     private String indexName;
 5     @ExportFieldAnnotation
 6     private String indexRule;
 7     @ExportFieldAnnotation
 8     private String indexField;
 9     @ExportFieldAnnotation
10     private Integer indexType;//1 私有  2 公有
11     @ExportFieldAnnotation
12     private Integer sort;
13 
14   //getter and setter
15 }

最后,在导出的时候,通过反射获取到该对象属性的注解,完成业务规则:

 1  public static String genTitle(Field[] fAll){
 2         List titles = new ArrayList<>();
 3         for(int i=0;i<fAll.length;i++){
 4             //获取该字段所有的注解
 5             Annotation[] annotations = fAll[i].getDeclaredAnnotations();
 6             for(Annotation annotation : annotations){
 7                 //只获取指定注解的字段
 8                 if(annotation instanceof ExportFieldAnnotation){
 9                     titles.add(fAll[i].getName());
10                 }
11             }
12         }
13         String s = StringUtils.join(titles,",");
14         logger.info("export titles :" + s );
15         return s;
16     }

可以看到,对传进来的 field 数组,遍历循环,当属性的注解包含我们自定义的注解的时候,才把这个字段写入到 title 当中去。

下面我们整理一下几个元注解的含义(以下摘抄自:http://www.cnblogs.com/peida/archive/2013/04/24/3036689.html):

            1. @Target:

    说明了 Annotation 所修饰的对象范围:Annotation 可被用于 packages、types(类、接口、枚举、Annotation 类型)、类型成员(方法、构造方法、成员变量、枚举值)、方法参数和本地变量(如循环变量、catch 参数)。在 Annotation 类型的声明中使用了 target 可更加明晰其修饰的目标。

       取值 (ElementType) 有:

    1.CONSTRUCTOR: 用于描述构造器
    2.FIELD: 用于描述域
    3.LOCAL_VARIABLE: 用于描述局部变量
    4.METHOD: 用于描述方法
    5.PACKAGE: 用于描述包
    6.PARAMETER: 用于描述参数
    7.TYPE: 用于描述类、接口 (包括注解类型) 或 enum 声明

    2.@Retention:

    @Retention 定义了该 Annotation 被保留的时间长短:某些 Annotation 仅出现在源代码中,而被编译器丢弃;而另一些却被编译在 class 文件中;编译在 class 文件中的 Annotation 可能会被虚拟机忽略,而另一些在 class 被装载时将被读取(请注意并不影响 class 的执行,因为 Annotation 与 class 在使用上是被分离的)。使用这个 meta-Annotation 可以对 Annotation 的“生命周期”限制。

作用:表示需要在什么级别保存该注释信息,用于描述注解的生命周期(即:被描述的注解在什么范围内有效)

  取值(RetentionPoicy)有:

    1.SOURCE: 在源文件中有效(即源文件保留)
    2.CLASS: 在 class 文件中有效(即 class 保留)
    3.RUNTIME: 在运行时有效(即运行时保留)


   3.@Documented:

  @Documented 用于描述其它类型的 annotation 应该被作为被标注的程序成员的公共 API,因此可以被例如 javadoc 此类的工具文档化。Documented 是一个标记注解,没有成员。


   4.@Inherited:

 

      @Inherited 元注解是一个标记注解,@Inherited 阐述了某个被标注的类型是被继承的。如果一个使用了 @Inherited 修饰的 annotation 类型被用于一个 class,则这个 annotation 将被用于该 class 的子类。

 

  注意:@Inherited annotation 类型是被标注过的 class 的子类所继承。类并不从它所实现的接口继承 annotation,方法并不从它所重载的方法继承 annotation。

 

  当 @Inherited annotation 类型标注的 annotation 的 Retention 是 RetentionPolicy.RUNTIME,则反射 API 增强了这种继承性。如果我们使用 java.lang.reflect 去查询一个 @Inherited annotation 类型的 annotation 时,反射代码检查将展开工作:检查 class 和其父类,直到发现指定的 annotation 类型被发现,或者到达类继承结构的顶层。

           5. 自定义注解:

      使用 @interface 自定义注解时,自动继承了 java.lang.annotation.Annotation 接口,由编译程序自动完成其他细节。在定义注解时,不能继承其他的注解或接口。@interface 用来声明一个注解,其中的每一个方法实际上是声明了一个配置参数。方法的名称就是参数的名称,返回值类型就是参数的类型(返回值类型只能是基本类型、Class、String、enum)。可以通过 default 来声明参数的默认值。

  定义注解格式:
  public @interface 注解名 {定义体}

  注解参数的可支持数据类型:

    1. 所有基本数据类型(int,float,boolean,byte,double,char,long,short)
    2.String 类型
    3.Class 类型
    4.enum 类型
    5.Annotation 类型
    6. 以上所有类型的数组

  Annotation 类型里面的参数该怎么设定: 
  第一, 只能用 public 或默认 (default) 这两个访问权修饰. 例如,String value(); 这里把方法设为 defaul 默认类型;   
  第二, 参数成员只能用基本类型 byte,short,char,int,long,float,double,boolean 八种基本数据类型和 String,Enum,Class,annotations 等数据类型, 以及这一些类型的数组. 例如,String value(); 这里的参数成员就为 String;  
  第三, 如果只有一个参数成员, 最好把参数名称设为 "value", 后加小括号。

 

明白了自定义注解怎么使用了,下面我们来看一个更加经典的使用场景:

为每一个接口加一个 @ExecTime,实现计算每一个接口从请求到返回的时间。

首先,我们自定义一个注解:

1 @Target(ElementType.METHOD)
2 @Retention(RetentionPolicy.RUNTIME)
3 @Documented
4 public @interface ExecTime {
5     String value() default "";
6 }

然后,我们通过 aspectj 去实现注解的业务:

@Aspect
@Component
public class MethodTimeAspect {
    private final static Logger logger = LoggerFactory.getLogger(MethodTimeAspect.class);
@Pointcut(</span>"@annotation(com.usst.user.auth.annotation.ExecTime)"<span style="color: rgba(0, 0, 0, 1)">)
</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> pointCut() {
}

@Around(</span>"pointCut()"<span style="color: rgba(0, 0, 0, 1)">)
</span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> Object useTime(ProceedingJoinPoint joinPoint) {
    Object out </span>= <span style="color: rgba(0, 0, 255, 1)">null</span><span style="color: rgba(0, 0, 0, 1)">;
    </span><span style="color: rgba(0, 0, 255, 1)">try</span><span style="color: rgba(0, 0, 0, 1)"> {
        String className </span>=<span style="color: rgba(0, 0, 0, 1)"> joinPoint.getTarget().getClass().getSimpleName();
        logger.info(String.format(</span>" Method [%s.%s()] start"<span style="color: rgba(0, 0, 0, 1)">, className, joinPoint.getSignature().getName()));
        </span><span style="color: rgba(0, 0, 255, 1)">long</span> start =<span style="color: rgba(0, 0, 0, 1)"> System.currentTimeMillis();
        out </span>=<span style="color: rgba(0, 0, 0, 1)"> joinPoint.proceed();
        </span><span style="color: rgba(0, 0, 255, 1)">long</span> elapsedTime = System.currentTimeMillis() -<span style="color: rgba(0, 0, 0, 1)"> start;
        logger.info(String.format(</span>" Method [%s.%s()] execution time:%sms"<span style="color: rgba(0, 0, 0, 1)">, className, joinPoint.getSignature().getName(), elapsedTime));
    } </span><span style="color: rgba(0, 0, 255, 1)">catch</span><span style="color: rgba(0, 0, 0, 1)"> (Throwable throwable) {
        logger.error(</span>"aop record method exec time error"<span style="color: rgba(0, 0, 0, 1)">, throwable);
    }
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> out;
}

}

这样,我们完成了在这个自定义注解的方法上,织入了打印请求时间和请求响应耗时的业务,只需要在对应的 controller 层上的接口,加上对应的注解就可以了。