Spring Boot AOP @Pointcut拦截注解的表达式与运算符
项目场景:
这里主要说下Spring Boot AOP中@Pointcut拦截类上面的注解与方法上面的注解,怎么写表达式怎么,还有@Pointcut中使用运算符。
@PointCut 表达式
拦截注解的表达式有3种:@annotation、@within、@target
1、@annotation
匹配有指定注解的方法(注解作用在方法上面)
@annotation(com.test.aop.demo.MyAnnotation)
2、@within
匹配包含某个注解的类(注解作用在类上面)
@within(com.test.aop.demo.MyAnnotation)
3、@target
匹配目标对象有指定注解的类(注解作用在类上面)
@target(com.test.aop.demo.MyAnnotation)
@target 和@within的区别:
1、@target(注解A):判断被调用的目标对象中是否声明了注解A,如果有,会被拦截;2、@within(注解A): 判断被调用的方法所属的类中是否声明了注解A,如果有,会被拦截;
3、@target关注的是被调用的对象,@within关注的是调用的方法所在的类;
@PointCut中的运算符
PointCut中可以使用&&、||、! 运算符
同时匹配方法上的和类上的注解
@Pointcut("@annotation(com.test.aop.demo.MyAnnotation) || @within(com.test.aop.demo.MyAnnotation)")
public void cutController(){
}
或者
@Pointcut("@annotation(com.test.aop.demo.MyAnnotation)")
public void cutController(){
}@Pointcut("@within(com.test.aop.demo.MyAnnotation)")
public void cutService(){
}@Pointcut("cutController() || cutService()")
public void cutAll(){
}