Spring Aop 自定义类注解和方法注解作为切点

这篇博客介绍了如何创建一个自定义注解,该注解可以应用于类和方法,并在运行时通过AOP切面处理。当注解同时存在类和方法上时,方法上的注解具有更高的优先级。示例代码展示了如何使用@Retention(RUNTIME)和@Target(ElementType)来定义注解,并通过@Aspect和@Pointcut在Spring AOP中处理注解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用途:
使一个注解既能修饰类也能修饰方法,当同时修饰类和方法时,方法注解优先级更高。

  1. 自定义注解
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface TestAnnotation {
    String value() default "";
}
  1. 编写切面
@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;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值