1.元注解
元注解就是定义注解的注解,是Java提供的用于定义注解的基本注解
1.@Target
该注解的作用是告诉Java将自定义的注解放在什么地方,比如类、方法、构造器、变量上等。 它的值是一个枚举类型,有如下属性值。
- ElementType.CONSTRUCTOR:用于描述构造器。
- ElementType.FIELD:用于描述成员变量、对象、属性(包括enum实例)。
- ElementType.LOCAL_VARIABLE:用于描述局部变量。
- ElementType.METHOD:用于描述方法。
- ElementType.PACKAGE:用于描述包。
- ElementType.PARAMETER:用于描述参数。
- ElementType.TYPE;用于描述类、接口(包括注解类型)或enum声明。
2.@Retention
该注解用于说明自定义注解的生命周期,在注解中有三个生命周期.
- RetentionPolicy.RUNTIME:始终不会丢弃,运行期也保留该注解,可以使用反射机制读取该注解的信息。自定义的注解通常使用这种方式。
- RetentionPolicy.CLASS:类加载时丢弃,默认使用这种方式。
- RetentionPolicy.SOURCE:编译阶段丢弃,自定义注解在编译结束之后就不再有意义, 所以它们不会写入字节码。@Override @SuppressWarnings都属于这类注解。
3.@Inherited
该注解是一个标记注解,表明被标注的类型是可以被继承的。如果一个使用了@lnherited修饰 的Annotation类型被用于一个Class,则这个Annotation将被用于该Class的子类。
4.@Documented
该注解表示是否将注解信息添加在Java文档中。
5.@interface
该注解用来声明一个注解,其中的每一个方法实际上是声明了一个配置参数。方法的名称就是参数的名称,返回值类型就是参数的类型(返回值类型只能是基本类型、Class、String、enum)。 可以通过default来声明参数的默认值。
2.自定义注解
1.创建自定义注解类
package com.itheima.annotation;
import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.stereotype.Component; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target;
@Target({ElementType.METHOD,ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Document @Component public @interface MyTestAnnotation { String value(); }
|
- 使用@Target 标注作用范围。
- 使用@Retention注解标注生命周期。
- 使用@Documented将注解信息添加在Java文档中。
2.实现业务逻辑
以AOP的方式实现业务逻辑
package com.itheima.domain;
import com.itheima.annotation.MyTestAnnotation; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.stereotype.Component; import java.lang.reflect.Method;
@Aspect @Component public class AnnotationInterface { @Pointcut("@annotation(com.itheima.annotation.MyTestAnnotation)") public void myAnnotationPointcut(){ } @Before("myAnnotationPointcut()") public void before(JoinPoint joinPoint) throws Exception { MethodSignature sign = (MethodSignature) joinPoint.getSignature(); Method method = sign.getMethod(); MyTestAnnotation annotation = method.getAnnotation(MyTestAnnotation.class); System.out.println("MyTestAnnotation:"+annotation.value()); } }
|
3.使用自定义注解
@MyTestAnnotation("测试用") @GetMapping("/list") public Flux<User> getAll(){ return userRepository.findAll(); }
|
运行上面代码,输出如下结果:
MyTestAnnotation:测试用