AOP中获取方法上的注解/参数

通过aop方式(自定义注解)对方法进行前置/环绕/后置等处理时,可以通过以下方法,在加强处理方法中获取被加强方法的参数和注解等内容

 

自定义注解

@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface OperationLog {
    String description() default "";
}

aop类

@Aspect
@Component
public class WebOperationRecordHandle {
    
    @Pointcut("@annotation(com.test.aspect.OperationLog)")
    public void operationAspect() {
        
    }

    /*
    * 将被加强类的注解传入方法参数
    */
    @Before(value = "operationAspect() && @annotation(operationLog)", argNames = "operationLog")
    public void beforeHandel(OperationLog operationLog) {
        String description = operationLog.description();
        System.out.println(description);
    }

被加强的类

    @OperationLog(description = "测试方法")
    public Json test() {

    }

 

以下为获取被加强方法其他内容的写法

@Around(value = "args(param) && target(bean) && @annotation(logAnnotation)", argNames = "jp, param, bean, logAnnotation")
public void before(JoinPoint jp, String param, PersonService bean, LogAnnotation logAnnotation) {  
    ...
}

参考博客: http://loveshisong.cn/%E7%BC%96%E7%A8%8B%E6%8A%80%E6%9C%AF/2016-06-01-AOP%E4%B8%AD%E8%8E%B7%E5%8F%96%E6%96%B9%E6%B3%95%E4%B8%8A%E7%9A%84%E6%B3%A8%E8%A7%A3%E4%BF%A1%E6%81%AF.html

 

 

安利一门Python超级好课!
扫码下单输优惠码【csdnfxzs】再减5元,比官网还便宜!

https://marketing.csdn.net/u/xizolv/e/109

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值