Springboot AOP获取对象上的注解

写在前面

因为业务需求需要获取Class上的注解,然后网上博客的获取方法师出同门,但是实践后发现获取不了,就只有自己看一下到底问题在哪儿了,仅此记录一下。

获取方式

其他获取方式点击传送到对应博客

// 大致代码如下
joinPoint.getTarget().getClass().getAnnotation(CustomerAnnotation.class);

自己获取方式

// 这里获取的对象是一个Annotation对象,但是的确能获取对象上的注解
// joinPoint.getTarget().getClass()只能获取到代理对象proxy
proceedingJoinPoint.getSignature().getDeclaringType().getAnnotation(CustomerAnnotation.class);
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值