Spring學習外傳(一) @Target、@Retention、@Documented簡介

怎麼說呢,這三個註解是我在看SpringBoot源碼的時候看到的,因爲沒有看過spring源碼,也不清楚有沒有,姑且先暫時算在spring學習裏,等把spring吃透了再回來看

先來看一個一個常用註解@Controller

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
 
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Controller {
 
	/**
	 * The value may indicate a suggestion for a logical component name,
	 * to be turned into a Spring bean in case of an autodetected component.
	 * @return the suggested component name, if any
	 */
	String value() default "";
 
}

@interface 定義註解的時候,上面有四個註解, @Component就不說了,我們看一下剩下三個註解

正片開始:

1. @Target({ElementType.TYPE}) 註解

ElementType 這個枚舉類型的常量提供了一個簡單的分類:註釋可能出現在Java程序中的語法位置(這些常量與元註釋類型(@Target)一起指定在何處寫入註釋的合法位置)


package java.lang.annotation;
 
/**
 * The constants of this enumerated type provide a simple classification of the
 * syntactic locations where annotations may appear in a Java program. These
 * constants are used in {@link Target java.lang.annotation.Target}
 * meta-annotations to specify where it is legal to write annotations of a
 * given type.
 * @author  Joshua Bloch
 * @since 1.5
 * @jls 9.6.4.1 @Target
 * @jls 4.1 The Kinds of Types and Values
 */
public enum ElementType {
    /** 類, 接口 (包括註釋類型), 或 枚舉 聲明 */
    TYPE,
 
    /** 字段聲明(包括枚舉常量) */
    FIELD,
 
    /** 方法聲明(Method declaration) */
    METHOD,
 
    /** 正式的參數聲明 */
    PARAMETER,
 
    /** 構造函數聲明 */
    CONSTRUCTOR,
 
    /** 局部變量聲明 */
    LOCAL_VARIABLE,
 
    /** 註釋類型聲明 */
    ANNOTATION_TYPE,
 
    /** 包聲明 */
    PACKAGE,
 
    /**
     * 類型參數聲明
     *
     * @since 1.8
     */
    TYPE_PARAMETER,
 
    /**
     * 使用的類型
     *
     * @since 1.8
     */
    TYPE_USE
}

2.@Retention({RetentionPolicy.Runtime}) 註解

RetentionPolicy這個枚舉類型的常量描述保留註釋的各種策略,它們與元註釋(@Retention)一起指定註釋要保留多長時間

package java.lang.annotation;
/**
 * Annotation retention policy.  The constants of this enumerated type
 * describe the various policies for retaining annotations.  They are used
 * in conjunction with the {@link Retention} meta-annotation type to specify
 * how long annotations are to be retained.
 *
 * @author  Joshua Bloch
 * @since 1.5
 */
public enum RetentionPolicy {
    /**
     * 註釋只在源代碼級別保留,編譯時被忽略
     */
    SOURCE,
    /**
     * 註釋將被編譯器在類文件中記錄
     * 但在運行時不需要JVM保留。這是默認的
     * 行爲.
     */
    CLASS,
    /**
     *註釋將被編譯器記錄在類文件中
     *在運行時保留VM,因此可以反讀。
     * @see java.lang.reflect.AnnotatedElement
     */
    RUNTIME
}

3. @Documented註解

Documented註解表明這個註釋是由 javadoc記錄的,在默認情況下也有類似的記錄工具。 如果一個類型聲明被註釋了文檔化,它的註釋成爲公共API的一部分。

很簡單,單往往簡單的運用才能體現出真正的技術,加油一起學習吧!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章