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 { }