@Slf4j
@Aspect
@Component
public class ApiOperationAspect extends StaticMethodMatcherPointcutAdvisor implements MethodInterceptor {
@Override
public Advice getAdvice() {
return this;
}
@Override
public ClassFilter getClassFilter() {
return clazz -> AnnotatedElementUtils.hasAnnotation(clazz, Controller.class) ||
AnnotatedElementUtils.hasAnnotation(clazz, RestController.class);
}
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
log.info("{}", "开始执行我的方法。。。。。");
ApiOperation apiOperation = MyAnnotationUtil.getMethodAnnotation(invocation.getMethod(), ApiOperation.class);
if (apiOperation != null) {
log.info("value={}", apiOperation.value());
}
return invocation.proceed();
}
@Override
public boolean matches(Method method, Class<?> aClass) {
return MyAnnotationUtil.getMethodAnnotation(method, ApiOperation.class) != null;
}
}
public final class MyAnnotationUtil{
private MyAnnotationUtil(){
}
private static MyAnnotationHelper annotationHelper = new MyAnnotationHelper();
public static <T extends Annotation> T getMethodAnnotation(Method method, Class<T> annotationClass) {
return annotationHelper.getMethodAnnotation(method, annotationClass);
}
}
final class MyAnnotationHelper {
private ConcurrentMap<AnnotationCacheKey, Annotation> cache;
MyAnnotationHelper () {
cache = new ConcurrentHashMap<>();
}
@SuppressWarnings("unchecked")
public <T extends Annotation> T getMethodAnnotation(Method method, Class<T> annotationClass) {
return (T) cache.computeIfAbsent(new AnnotationCacheKey(method, annotationClass), key-> computeMethodAnnotation(method, annotationClass));
}
}