缘起
在前面的文章中,我们使用了注解@ConditionalOnClass,在此注解上面有其它的注解,在自定义注解的时候,如果不明白上面的这些配置,那可能就会搞错这个注解的使用。
一、元注解
1.1 元注解的源码结构
从java.lang.annotation包截图看,一共定义了6个注解:
(1)@Document
(2)@Target
(3)@Retention
(4)@Inherited
(5)@Native
(6)@Repeatable
其中前4个是元注解
1.2 元注解的定义
所谓元注解就是注解的注解,元注解负责注解自定义注解,你可以看到许多自定义的注解上面都有这些元注解:
例如Spring Boot的注解@ConditionalOnClass:
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(OnClassCondition.class)
public @interface ConditionalOnClass {
Class<?>[] value() default {};
String[] name() default {};
}
1.3 元注解的用途
1.3.1 @Target:注解的使用范围
标识注解的使用范围,可以赋值为ElementType类型,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
}
1.3.2 @Documented:是否要被写入javadoc
@Document注解用途主要是标识类型是否要被收入javadoc
1.3.3 @Inherited:是否可以被子类继承
说明子类可以继承父类中的该注解
1.3.4 @Retention:注解保留的位置
注解的保留位置,可以赋值 RetentionPolicy类型,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
}
(1)RetentionPolicy.SOURCE:表明注解会被编译器丢弃,字节码中不会带有注解信息
(2)RetentionPolicy.CLASS:表明注解会被写入字节码文件,且是@Retention的默认值
(3)RetentionPolicy.RUNTIME:表明注解会被写入字节码文件,并且能够被JVM 在运行时获取到,可以通过反射的方式解析到
二、举例说明
2.1 @ConditionalOnClass
(1)@Target:说明该注解可以使用在TYPE(接口、类、枚举、注解)和METHOD(方法)上。
(2)@Retention(RetentionPolicy.RUNTIME):表明注解会被写入字节码文件,并且能够被JVM 在运行时获取到,可以通过反射的方式解析到。
(3)Documented:要写入到javadoc中。
。。。。。。。。。。。。。。。。。版权原因,完整文章,请参考如下:Spring Boot @ConditionalOnClass上的注解你了解多少-java元注解和注解 - 第404篇