可以通过新建Annotation,向新建的注解中添加参数和使用元注解来配置该注解,以此完成自定义注解
定义注解:
- 第一步,用
@interface
定义注解:
public @interface RequestMapping{
}
- 第二步,添加参数、默认值,如果没有默认值,就必须给参数赋值:
public @interface RequestMapping{
//参数类型 +参数名() +
String value() default "index";
}
把最常用的参数定义为value(),推荐所有参数都尽量设置默认值。
- 第三步,用元注解配置注解:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface RequestMapping{
String value() default "index";
}
其中,必须设置@Target
和@Retention
,@Retention
一般设置为RUNTIME
,因为我
们自定义的注解通常要求在运行期读取。一般情况下,不必写@Inherited
和@Repeatable
。
在使用的时候,如果一个类用到了我们定义的注解,则它的子类也定义该注解。此处要注意当我们向类或方法上添加元注解@Target
和@Retention
时,可能会报错,需要手动导入:
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.ElementType;
元注解
-
元注解的作用就是负责注解其他注解,Java定义了4个标准的元注解类型,他们被用来提供对其他注解类型作说明
-
这些类型和他们所支持的类在java.lang.annotation包中可以找到
1、@Target:用于描述注解的使用范围- 类或接口:
ElementType.TYPE
; - 字段:
ElementType.FIELD
; - 方法:
ElementType.METHOD
; - 构造方法:
ElementType.CONSTRUCTOR
; - 方法参数:
ElementType.PARAMETER
。
可以设置多个范围:
@Target(value ={ElementType.METHOD,ElementType.TYPE})
2、@Retention:表示需要在什么级别保存该注释信息,用于描述注解的生命周期
- 仅编译期:
RetentionPolicy.SOURCE
; - 仅class文件:
RetentionPolicy.CLASS
; - 运行期:
RetentionPolicy.RUNTIME
。
范围:RUNTIME>CLASS>SOURCE
如果@Retention不存在,则该Annotation默认为CLASS。因为通常我们自定义的Annotation都是RUNTIME,所以,务必要加上@Retention(RetentionPolicy.RUNTIME)这个元注解;
3、@Document:说明该注将被包含在javadoc中
4、@Iherited:使用@Inherited定义子类是否可继承父类定义Annotation。 - 类或接口:
@Inherited仅针对 @Target(ElementType.TYPE)类型的annotation有效,并且仅针对
class的继承,对interface的继承无效:
@Inherited
@Target(ElementType.TYPE)
public @interface RequestMapping{
String value() default "index";
}