AOP通过反射获取自定义注解

 自定义注解:

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface DemoAnno {
    String value()  default "";
}

AOP: 

@Pointcut("@annotation(com.hephae.aop.aop.DemoAnno)")
    public void demoAspect() {
    }

    @Around(value = "demoAspect()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature)signature;
        //method为接口的Method对象,获取不到实现类方法上的注解
        Method method = methodSignature.getMethod();
        //targetMethod为实现类方法对象
        Method targetMethod = joinPoint.getTarget().getClass().getMethod(method.getName(), method.getParameterTypes());
        //获取注解
        DemoAnno demoAnno = targetMethod.getAnnotation(DemoAnno.class);
        if (demoAnno != null) {
            String value = demoAnno.value();
        }
        Object obj = null;
        obj = joinPoint.proceed();
        return obj;
    }    

 

转载于:https://www.cnblogs.com/hephae/p/7284293.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
获取自定义注解修饰的Controller参数值,可以使用 AOP 的方法拦截请求,并在拦截方法中获取参数值。具体步骤如下: 1. 定义一个自定义注解,例如 @MyAnnotation。 2. 在需要拦截的 Controller 方法参数上添加 @MyAnnotation 注解。 3. 编写一个切面类,在类上添加 @Aspect 注解,并定义一个切点方法,使用 @Around 注解指定需要拦截的方法。 4. 在切点方法中,使用 JoinPoint 对象获取目标方法的参数,通过反射获取参数上的 @MyAnnotation 注解,从而获取注解中的值。 示例代码如下: ```java @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PARAMETER) public @interface MyAnnotation { String value(); } @Controller public class UserController { @GetMapping("/users/{id}") public String getUser(@MyAnnotation("user_id") @PathVariable Long id) { // ... } } @Aspect @Component public class MyAspect { @Around("execution(* com.example.controller.*.*(..))") public Object around(ProceedingJoinPoint point) throws Throwable { Object[] args = point.getArgs(); for (Object arg : args) { MyAnnotation annotation = arg.getClass().getAnnotation(MyAnnotation.class); if (annotation != null) { String value = annotation.value(); // TODO: 处理注解值 } } return point.proceed(); } } ``` 在上面的示例中,我们定义了一个 @MyAnnotation 注解,用于修饰 Controller 方法的参数。在 UserController 中,我们使用 @MyAnnotation 注解修饰了 getUser 方法的 id 参数,注解的值为 "user_id"。 然后,在 MyAspect 类中,我们使用 @Around 注解指定需要拦截的方法,并通过 JoinPoint 对象获取目标方法的参数。我们遍历参数列表,使用反射获取参数上的 @MyAnnotation 注解,并从注解中获取值,最终可以进行处理。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值