Spring的元注解:注解上的注解。
1.@Target(ElementType.TYPE)
使用java.lang.annotation.Target可以定义其使用时机,在定义时要时要指定java.lang.annotaton.ElementType的枚举值之一。
@Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.ANNOTATION_TYPE) public @interface Target { /** * Returns an array of the kinds of elements an annotation type * can be applied to. * @return an array of the kinds of elements an annotation type * can be applied to */ ElementType[] value(); }
下面看一下ElementType:
public enum ElementType { /** Class, interface (including annotation type), or enum declaration */ TYPE, /** Field declaration (includes enum constants) */ FIELD, /** Method declaration */ METHOD, /** Formal parameter declaration */ PARAMETER, /** Constructor declaration */ CONSTRUCTOR, /** Local variable declaration */ LOCAL_VARIABLE, /** Annotation type declaration */ ANNOTATION_TYPE, /** Package declaration */ PACKAGE, /** * Type parameter declaration * * @since 1.8 */ TYPE_PARAMETER, /** * Use of a type * * @since 1.8 */ TYPE_USE }
ANNOTATION_TYPE: 注解只能修饰注解,不能修饰其他的东西
CONSTRUCTOR: 注解只能修饰构造方法
FIELD: 注解只能修饰属性(成员变量)
LOCAL_VARIABLE: 注解只能修饰局部变量
METHOD: 注解只能修饰方法
PACKAGE: 注解只能修饰包
PARAMETER: 注解只能修饰方法的参数
TYPE: 注解只能修饰类、接口、枚举
2.@Retention(RetentionPolicy.RUNTIME)
@Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.ANNOTATION_TYPE) public @interface Retention { /** * Returns the retention policy. * @return the retention policy */ RetentionPolicy value(); }
下面看一下RetentionPolicy:
public enum RetentionPolicy { /** * Annotations are to be discarded by the compiler. */ SOURCE, /** * Annotations are to be recorded in the class file by the compiler * but need not be retained by the VM at run time. This is the default * behavior. */ CLASS, /** * Annotations are to be recorded in the class file by the compiler and * retained by the VM at run time, so they may be read reflectively. * * @see java.lang.reflect.AnnotatedElement */ RUNTIME }
SOURCE:编译程序处理完Annotation信息后就完成任务,编译时忽略 CLASS:编译程序将Annotation存储于class档中,JVM忽略 RUNTIME:编译程序将Annotation储存于class档中,可由VM使用反射机制的代码所读取和使用。
3.Documented
Documented 注解表明这个注解应该被 javadoc工具记录. 默认情况下,javadoc是不包括注解的. 但如果声明注解时指定了 @Documented,则它会被 javadoc 之类的工具处理, 所以注解类型信息也会被包括在生成的文档中。
@Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.ANNOTATION_TYPE) public @interface Documented { }
4.@Inherited
这是一个稍微复杂的注解类型. 它指明被注解的类会自动继承. 更具体地说,如果定义注解时使用了 @Inherited 标记,然后用定义的注解来标注另一个父类, 父类又有一个子类(subclass),则父类的所有属性将被继承到它的子类中.
@Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.ANNOTATION_TYPE) public @interface Inherited { }