在aop记录输出记录,或者进行日志存储数据库时候,都是需要自定义注解来标记方法的,但如何获得注解里面的数据,如何用注解切入,是很多人不知道的,今天就让我们搞定这个问题!
一、创建注解类
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface DiaryNote {
String message() default "";
String type() default "";
}
2、在Service上的方法添加注释
3、aop切面拦截注解,实现对象取值
@Pointcut("@annotation(com.example.spring.mapper.DiaryNote)")
public void DiaryMapper() {
}
@AfterReturning(pointcut = "DiaryMapper()", returning = "result")
public void logPostMapping(JoinPoint joinPoint, Object result) {
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
DiaryNote redis = (DiaryNote) method.getAnnotation(DiaryNote.class);
System.out.println(redis.message())
System.out.println(redis.type())
}