spring aop 拦截自定义注解的类和方法
在之前需要了解 @within 和 @annotation 的区别
- @within: 拦截类上
- @annotation: 拦截方法上
自定义注解
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface AD {
String value();
}
自定义切面
@Configuration
@Aspect
public class DataSourceAspect2 {
@Pointcut("@within(com.xx.config.datasource.AD)||@annotation(com.xx.config.datasource.AD)")
public void pointCut() {}
@Before("pointCut()")
public void changeDataSource(JoinPoint point) throws Throwable {
MethodSignature signature = (MethodSignature) point.getSignature();
Method method = signature.getMethod();
AD annotation = method.getAnnotation(AD.class);
if (annotation == null) {
annotation = method.getDeclaringClass().getAnnotation(AD.class);
}
System.out.println("annotation: " + annotation.value());
}
}