MethodInterceptor
1 依赖
springboot的2.3.0.RELEASE版本构建,需要导入aop的starter;
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2 第一种 AspectJExpressionPointcut定义切点
public class MyInterceptor implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
System.out.println(methodInvocation.getMethod().getName());
return methodInvocation.proceed();
}
}
@Configuration
public class InterceptorConfig {
//注意该地址为项目具体包地址
public static final String traceExecution = "execution(* com.example.methodinterceptor..*.*(..))";
@Bean
public DefaultPointcutAdvisor defaultPointcutAdvisor2() {
MyInterceptor interceptor = new MyInterceptor();
AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
pointcut.setExpression(traceExecution);
// 配置增强类advisor
DefaultPointcutAdvisor advisor = new DefaultPointcutAdvisor();
advisor.setPointcut(pointcut);
advisor.setAdvice(interceptor);
return advisor;
}
}
3 第二种 JdkRegexpMethodPointcut来构造切点
public class MyInterceptor implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
System.out.println(methodInvocation.getMethod().getName());
return methodInvocation.proceed();
}
}
@Configuration
public class InterceptorConfig {
@Bean
public DefaultPointcutAdvisor defaultPointcutAdvisor() {
JdkRegexpMethodPointcut pointcut = new JdkRegexpMethodPointcut();
pointcut.setPattern("com.example.methodinterceptor.*");
// 配置增强类advisor
DefaultPointcutAdvisor advisor = new DefaultPointcutAdvisor();
advisor.setPointcut(pointcut);
advisor.setAdvice(new MyInterceptor());
System.out.println(advisor.toString());
return advisor;
}
}
4 第三种
只是在第一种基础上,将AspectJExpressionPointcut的参数改变了Expression;
直接使用案例一代码,然后将traceExecution修改就可以了
public static final String traceExecution = “annotation(com.example.methodinterceptor.annotation.InterceptorAnnotation)”;
5 第四种 AnnotationMatchingPointcut来构造切点
public class MyInterceptor implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
System.out.println(methodInvocation.getMethod().getName());
return methodInvocation.proceed();
}
}
使用AnnotationMatchingPointcut构造切点
注意: 这是使用的AnnotationMatchingPointcut构造方法;在参考文章1中使用的是:
AnnotationMatchingPointcut pointcut = new AnnotationMatchingPointcut(InterceptorAnnotation.class, true);
这个写法并没有对该注解进行拦截;在文章末尾的评论有提到这个问题;
@Configuration
public class InterceptorConfig {
@Bean
public Advisor pointcutAdvisor() {
MyInterceptor interceptor = new MyInterceptor();
AnnotationMatchingPointcut pointcut = new AnnotationMatchingPointcut(null,InterceptorAnnotation.class);
// 配置增强类advisor
DefaultPointcutAdvisor advisor = new DefaultPointcutAdvisor();
advisor.setPointcut(pointcut);
advisor.setAdvice(interceptor);
System.out.println(advisor.toString());
return advisor;
}
}