用途:
使一个注解既能修饰类也能修饰方法,当同时修饰类和方法时,方法注解优先级更高。
- 自定义注解
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface TestAnnotation {
String value() default "";
}
- 编写切面
@Aspect
@Component
public class TestAop {
@Pointcut("@within(org.example.douban.search.aop.TestAnnotation) || @annotation(org.example.douban.search.aop.TestAnnotation)")
public void pointcut() {
}
@Around("pointcut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
try {
MethodSignature methodSignature = (MethodSignature) point.getSignature();
Method method = methodSignature.getMethod();
// 从方法上获取注解
TestAnnotation testAnnotation = method.getAnnotation(TestAnnotation.class);
if (testAnnotation == null) {
// 若方法上找不到, 从类上获取注解
Class<?> declaringClass = method.getDeclaringClass();
testAnnotation = declaringClass.getAnnotation(TestAnnotation.class);
}
System.out.println("annotation: " + testAnnotation);
return point.proceed();
} catch (Throwable throwable) {
System.out.println("异常了:" + throwable);
throw throwable;
}
}
}