在Java开发中,会用到很多注解,比如@Autowired,@Bean,这些是SpringBoot框架给我们封装好的,那如何去编写属于自己的注解呢?
一.元注解@Target
1.@Target可以定义Annotation能够被应用于源码的哪些位置
2.
- 类或接口:ElementType.TYPE;
- 字段:ElementType.FIELD;
- 方法:ElementType.METHOD;
- 构造方法:ElementType.CONSTRUCTOR;
- 方法参数:ElementType.PARAMETER。
@Retention
1.定义了Annotation的生命周期
2.
- 仅编译期:RetentionPolicy.SOURCE;
- 仅class文件:RetentionPolicy.CLASS;
- 运行期:RetentionPolicy.RUNTIME。
如果@Retention不存在,则该Annotation默认为CLASS
@Repeatable
1.定义Annotation是否可重复
@Inherited
1.定义子类是否可继承父类定义的Annotation,@Inherited仅针对@Target(ElementType.TYPE)类型的annotation有效,并且仅针对class的继承,对interface的继承无效
二.定义注解1.用@interface定义注解
2.添加参数、默认值:
3.用元注解配置注解:
必须设置@Target和@Retention,@Retention一般设置为RUNTIME
三.例子@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@documented
public @interface ReleaseManager {
String rbacApp() default "xx";
String handler() default "release";
boolean needQA() default false;
}



