java基础——注解部分

1. 注解的作用

元数据可以用来创建文档(用过Javadoc的注释自动生成文档),跟踪代码的依赖性,执行编译时格式检查,代替已有的配置文件。如果要对于元数据的作用进行分类,目前还没有明确的定义,不过我们可以根据它所起的作用,大致可分为三类:
1. 编写文档:通过代码里标识的元数据生成文档
2. 代码分析:通过代码里标识的元数据对代码进行分析
3. 编译检查:通过代码里标识的元数据让编译器能实现基本的编译检查

本篇写作目的:
①快速理解Springboot 的@SpringBootApplication的原始代码
②回顾javaSE中关于注解的相关知识。

//本处@Target就是限制了@SpringBootApplication的适用范围
//java提供了ElementType枚举类型来控制每个注释的适用范围
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {
      @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
      @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {
————————————————
版权声明:本文为CSDN博主「兴趣使然的草帽路飞」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_43591980/article/details/105475150

① 自定义注解类型

public @interface NewAnnotation{
}

②向自定义注解中添加变量

public @interface NewAnnotation{
    String value();//写注解时候value可以省略,但是有多个不同的String类型的变量时,每个变量的名字不可以省略
}

③为变量赋默认值

public @interface Greeting {
    public enum FontColor{
		RED,GREEN,BLUE
	}
	String title();
	String content();
	FontColor fontColor() default FontColor.RED;
}

④在注解的定义上使用@Target,可以限制注解的使用范围

public enum ElementType {
	TYPE,/** Class, interface (including annotation type), or enum
declaration */
	FIELD,/** Field declaration (includes enum constants) */
	METHOD,/** Method declaration */
	PARAMETER,/** Parameter declaration */
	CONSTRUCTOR,/** Constructor declaration */
	LOCAL_VARIABLE,/** Local variable declaration */
	ANNOTATION_TYPE,/** Annotation type declaration */
	PACKAGE /** Package declaration */
}

⑤@Retention,注解保持性策略

1、RetentionPolicy.SOURCE:注解只保留在源文件,当Java文件编译成class文件的时候,注解被遗弃;
2、RetentionPolicy.CLASS:注解被保留到class文件,但jvm加载class文件时候被遗弃,这是默认的生命周期;
3、RetentionPolicy.RUNTIME:注解不仅被保存到class文件中,jvm加载class文件之后,仍然存在;

package java.lang.annotation;
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.
 */
 RUNTIME
}

⑥@Document文档化功能

功能类似于javadoc,有利于开发人员定制Javadoc不支持的文档属性

@Document注解需要与@RententionPolicy.Runtime保持性策略联用

⑦@Inherit文档化功能

作用是控制注释是否会影响到子类


版权声明:本文为qq_41960905原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。