Springboot注解整理 二《自定义注解》

 

自定义注解

@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface CommonLog {

    String value() default "";
}
View Code

@Target

@Target 说明了Annotation所修饰的对象范围
取值ElementType 的类型如下所示:
public enum ElementType {
    /** 用于描述Class, interface (包括 annotation type),或 enum 声明 */
    TYPE,
    /** 用于描述域Field(包含枚举常量(enum)) */
    FIELD,
    /** 用于描述方法Method */
    METHOD,
    /** 用于描述参数parameter */
    PARAMETER,
    /** 用于描述构造器Constructor */
    CONSTRUCTOR,
    /** 用于描述局部变量Local variable */
    LOCAL_VARIABLE,
    /** Annotation type declaration */
    ANNOTATION_TYPE,
    /** 用于描述包Package */
    PACKAGE,
    /**
     * Type parameter declaration
     * @since 1.8
     */
    TYPE_PARAMETER,
    /**
     * Use of a type
     * @since 1.8
     */
    TYPE_USE
}

@Retention

@Retention定义了注解(Annotation)被保留的时间长短,RetentionPoicy源码如下所示:

public enum RetentionPolicy {
    /**
     * 说明所修饰的注解(Annotation)在编译时将被丢弃(即源文件保留)
     */
    SOURCE,
    /**
     * 注解(Annotation)将由编译器记录在类文件中,但不需要在运行时由VM保留。这是默认行为(即class保留)
     */
    CLASS,
    /**
     * 注解(Annotation)将由编译器记录在类文件中,并在运行时由VM保留,因此可以反射地读取注解。
     *(即运行时保留)
     * @see java.lang.reflect.AnnotatedElement
     */
    RUNTIME
}

@Inherited

1、@Inherited是元注解类型
2、指示自动继承注解(Annotation)类型。如果继承的元注解(meta-annotation)出现在注解(Annotation)类型声明上,并且用户在类声明上查询注解(Annotation)类型,并且类声明没有此类型的注解(Annotation),则将自动查询类的超类以查找注解(Annotation)类型。此过程将重复,直到找到此类型的注解(Annotation),或者到达类层次结构(对象)的顶部。如果没有超类具有此类型的注解(Annotation),则查询将指示相关类没有此类注解(Annotation)
3、请注意,如果元注解(meta-annotation)类型用于注释类以外的任何内容,则此元注释类型无效。还要注意,这个元注释只会导致注释从超类继承;实现接口上的注解(Annotation)没有效果。
@Documented
定义注解会被javadoc或者其他类似工具文档化
默认情况下,javadoc是不包括注解的. 但如果声明注解时指定了 @Documented,则它会被 javadoc 之类的工具处理 

实例

public class SxxService{
    
    @CommonLog("value")
    public  void  service(String  name){
          // ...  
    }

}

  

猜你喜欢

转载自www.cnblogs.com/outpointexception/p/10872691.html