SpringBoot注释之: @Target和@Retention @Target首先查看源代码,发现只有一个参数ElementType[] value ()
package java.lang.annotation; @ documented @ retention (retention policy.runtime ) target ) elementtype.annotation_type ) public @ interface target Rett type * canbeappliedto.* @ returnanarrayofthekindsofelementsanannotationtype * (kindsofelementsanannotationtype ) )。 }我们进入ElementType的源代码
package java.lang.annotation; public enum ElementType { /** Class,interface (includingannotationtype ),or enum declaration */TYPE,/* *字段解释(includesenumconstants ) * /字段,/** Method declaration */METHOD,/**formalparameterdeclaration/* * * formalparameterdeclaration/* * constructor declaration */constructor,/* * localvariabledeclaration */local /* * annotationtypedecllation/* * package declaration */package,/* * typeparameterdeclaration * * since 1.8 */typetype
@target(elementtype.field ) ——字段,枚举的常量
@target(elementtype.method ) ——方法
@target(elementtype.parameter ) ——方法参数
@ target (element type.constructor ) ——构造函数
@ target (element type.local _ variable ) ——局部变量
@ target (element type.annotation _ type ) ——注释
@target(elementtype.package ) ——包
@Retention虽然是个陈规,但是当我查看源代码时,我发现只有一个参数RetentionPolicy
package java.lang.annotation;/* * indicateshowlongannotationswiththeannotatedtypeareto * be retained.ifnoretentionannotationispresenton * an annnotation tion typtyped theretentionpolicydefaultsto * { @ coderetentionpolicy.class }.* * paretentionmeta-annotationhaseffectonlyifthe * meta-annotatedtypeisuseddirectlyforannotation.ith asno * effectifthemeta-annotatedtypeisusedasamembertypein * another @ since 1.5 * @ jls9.6.3.2@ retention */@ documented @ retention (retention ) ) retention @ target (element type.Anand ) returnstheretentionpolicy.* @ returnthereturnthe }进入此RetentionPolicy后,我们发现有三个值
package java.lang.annotation;/* * annotationretentionpolicy.theconstantsofthisenumeratedtype * describethevariouspoliciesforretainingannotations.theer inconjunctionwiththe { @ link retention } meta-annnotationtypetospecion howlongannotationsaretoberetained.* @ authorjoshons @ since 1.5 */publicenumretentionpolicy {/* * annotationsaretobedised/* * annotationsaretoberecordedintheclassfilebythecompiler * butneednotberetainedbythevmatruntime.thisisthedefault * behavilt/* * * annotationsaretoberecordedintheclassfilebythecompilerand * retainedbythevmatruntime,sotheymaybereadreflectively.*。
类型为RetentionPolicy.CLASS:的Annotations在编译时被保留,缺省保留策略位于class文件中,但JVM被忽略,并且在运行时无法检索。
类型的Annotations (如RetentionPolicy.RUNTIME: )由JVM保留,可以在运行时由JVM或其他使用反射的代码读取和使用。