springboot 集成 aop,ProceedingJoinPoint 对象详解

在Spring AOP中,ProceedingJoinPoint用于环绕通知(Around advice),通过它可以访问被通知方法的信息和参数。常用方法如下:

1. 获取切入点所在目标对象
proceedingJoinPoint.getTarget()

2. 获取切入点方法的名字
getSignature().getName()

3. 获取方法的参数
proceedingJoinPoint.getArgs()

4. 获取方法上的注解
        Object target = proceedingJoinPoint.getTarget();
        String methodName = proceedingJoinPoint.getSignature().getName();

        Method method = null;
        for (Method m : target.getClass().getMethods()) {
            if (m.getName().equals(methodName)) {
                System.out.println(Arrays.toString(m.getDeclaredAnnotations()));;
                break;
            }
        }

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,这是一个例子,展示了如何在Spring Boot中使用AOP获取对象及其引用的所有字段上的注解: 首先,我们需要一个自定义注解`@MyAnnotation`: ```java @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD}) public @interface MyAnnotation { String value() default ""; } ``` 然后,在需要被AOP处理的类或方法上添加`@MyAnnotation`注解: ```java @MyAnnotation public class UserController { @MyAnnotation private UserService userService; // other fields and methods } ``` 接着,我们创建一个切面类`MyAspect`,用于处理`@MyAnnotation`注解: ```java @Aspect @Component public class MyAspect { @Pointcut("@annotation(com.example.demo.MyAnnotation)") public void myPointcut() {} @Around("myPointcut()") public Object myAdvice(ProceedingJoinPoint joinPoint) throws Throwable { Object target = joinPoint.getTarget(); Field[] fields = target.getClass().getDeclaredFields(); for (Field field : fields) { MyAnnotation annotation = field.getAnnotation(MyAnnotation.class); if (annotation != null) { System.out.println("Found MyAnnotation on field: " + field.getName()); // do something with the annotation } } return joinPoint.proceed(); } } ``` 在`MyAspect`中,我们定义了一个切点`myPointcut`,用于匹配所有被`@MyAnnotation`注解的类或方法。然后,我们在`myAdvice`方法中,使用反射机制获取目标对象`target`,以及`target`引用的所有字段`fields`。在遍历`fields`的过程中,我们使用`field.getAnnotation(MyAnnotation.class)`方法获取字段上的`@MyAnnotation`注解,如果该注解存在,则说明该字段需要被处理。 最后,在Spring Boot应用程序中,将`MyAspect`类注册为一个Bean,以便AOP能够识别并应用它: ```java @SpringBootApplication @EnableAspectJAutoProxy public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @Bean public MyAspect myAspect() { return new MyAspect(); } } ``` 这样,当我们运行Spring Boot应用程序时,AOP就会自动识别`MyAspect`类,并在所有匹配到的类或方法上执行`myAdvice`方法。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值