Spring注解原理探索(一)

之 Java元注解釋義

Question
  • 注解在Java中如何起作用?
  • Spring是如何識別注解?
  • 如何自定義注解為我所用?
  • Spring注解:
    @Aotuwired @Required @Qualifier @Provider @Scope ...
  • Spring MVC 注解:
    @Controller @Service @Repository @Component @RequestMapping @RequetBody @ResponseBody ...
Extension
Solution

Java注解起源:JDK1.5
常見Java注解 :

  • @Override
  • @Deprecated
  • @SupressWarnings

1.從@Override說起,引出Java注解和元注解。
@Override 源碼如下:

/*If a method is annotated with this annotation type 
 * compilers are required to generate an error message 
 * unless at least one of the following conditions hold:
 *
 * The method does override or implement a method declared in a
 * supertype.
 * The method has a signature that is override-equivalent to that of
 * any public method declared in {@linkplain Object}.
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {    // @interface 修飾注解類
}

注意@Override 源碼中有3個要點:

  • @interface:修飾注解類使用@interface,而不是interface。這就定義了一個注解 @Override。
  • Java元注解:@Target, @Retention。Java元注解即:定義注解的注解(To annotate the annotation)。
  • 元注解參數(shù):ElementType.METHOD, RetentionPolicy.SOURCE

2.再看@Retention源碼(Retention: 保留,滯留之意。)

/* Indicates how long annotations with the annotated type are to
 * be retained.  If no Retention annotation is present on
 * an annotation type declaration, the retention policy defaults to
 * {@code RetentionPolicy.CLASS}.
 *
 * A Retention meta-annotation has effect only if the
 * meta-annotated type is used directly for annotation.  It has no
 * effect if the meta-annotated type is used as a member type in
 * another annotation type.
*/
@Documented     // 表明 注解會被包含在Java API文檔中。
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Retention {
    /**
     * Returns the retention policy.
     * @return the retention policy
     */
    RetentionPolicy value();
}
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
}

RetentionPolicy.SOURCE 保留在源碼級別,被編譯器拋棄,如@Override(如上@Override源碼);
RetentionPolicy.CLASS 被編譯器保留在編譯后的class文件,但是被VM拋棄;
RetentionPolicy.RUNTIME 保留至運行時,可以被反射讀取。如 @Retention 元注解本身。
** 引申1:如果定義一個注解需要被反射讀取,則在定義這個注解的時候?qū)⑻砑覢Retention(RetentionPolicy.RUNTIME) 元注解。**

3.再看@Target 元注解,定義了注解應該起作用的地方。

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

注解作用位置:

public enum ElementType {
    TYPE,                             // 類,接口(包括注解),enum;
    FIELD,                            // 屬性域
    METHOD,                           // 方法
    PARAMETER,                        // 參數(shù)
    CONSTRUCTOR,                      // 構(gòu)造函數(shù)
    LOCAL_VARIABLE,                   // 局部變量
    ANNOTATION_TYPE,                  // 注解類型
    PACKAGE,                          // 包

    /**
     * Type parameter declaration
     * @since 1.8
     */
    TYPE_PARAMETER,                   // 表明可以標注 類型參數(shù)

    /**
     * Use of a type
     * @since 1.8
     */
    TYPE_USE                          // 可以注解 任何類型名稱
}

** 引申2:如果想要自定義一個注解,就必須指定注解作用的位置。作用在 類,方法,屬性域,構(gòu)造函數(shù)等。 **

舉例 SpringMVC 中的 @RequestMapping。
其源碼定義如下:

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Mapping
public @interface RequestMapping {
    // skip its class code.
}

@RequestMapping 的@Target元注解 表明它可以被使用在方法和類(或接口,注解,enum)上。
@RequestMapping 的@Retention元注解表明它可以保留到運行時(RUNTIME),被反射讀取。

** 引申3:如果想要自定義注解,除了添加@interface 修飾類名,必須滿足上述引申1和引申2。 **
那么如何自定義注解?
請參考:Spring注解原理探索(二)之 Java中如何自定義注解

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,506評論 19 139
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 47,256評論 6 342
  • 本文章涉及代碼已放到github上annotation-study 1.Annotation為何而來 What:A...
    zlcook閱讀 29,735評論 15 116
  • 什么是注解(Annotation):Annotation(注解)就是Java提供了一種元程序中的元素關聯(lián)任何信息和...
    九尾喵的薛定諤閱讀 3,397評論 0 2
  • 我叫阿三,當然不是真名——只是被人這樣叫的時間長了,我連自己究竟是誰都忘了。其實叫阿三也沒什么不好,總比街道上那些...
    王霄垚閱讀 1,163評論 0 0

友情鏈接更多精彩內(nèi)容