AOP日志拦截注解参数方法及存在的问题
1、定义注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LogDes{
public String model() default "";
public String method() default "";
}
2、配置注解
//切点切入自己配置的那个注解
@Pointcut("@annotation(com.xxx.xx.LogDes)") //注意这里的写法@annotation() 切入注解
public void annotationLog(){} //随便取一个名字
这时候要注意,在获取代理对象时,如果用默认的代理对象,会获取不到配置AOP注解的的参数,要使用真实对象来获取,以下是代码。
@After("annotationLog()")
public void after(JoinPoint joinPoint){
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
//这个方法才是目标对象上有注解的方法
Method declaredMethod = joinPoint.getTarget().getClass().getDeclaredMethod(signature.getName(), method.getParameterTypes());
LogDes annotation declaredMethod .getAnnotation(LogDes.class);
System.out.println( annotation.model+annotation.method );
}
3、使用注解,放在要拦截的controller层
@LogDes(model="xx",method="xx")
@RequestMapping("/xxx")
public void xxx(){
......
}
参考博文
【1】AOP注解式拦截
【2】解决 getAnnotation为null的坑
扩展博客
【1】SpringBoot>15 - 自定义注解实现权限控制
【2】Spring Boot AOP 自定义注解实现权限控制
【3】02 AOP切入点详解