【问题标题】:Get HTTP Method from a joinPoint从 joinPoint 获取 HTTP 方法
【发布时间】:2020-01-14 22:56:26
【问题描述】:

我需要从一个方面的joinPoint获取像POST/PATCH/GET/etc这样的http方法。

@Before("isRestController()")
    public void handlePost(JoinPoint point) {
        // do something to get for example "POST" to use below 
        handle(arg, "POST", someMethod::getBeforeActions);
    }

point.getThis.getClass(),我得到了这个调用被拦截的控制器。然后,如果我从中获取方法,然后是注释。那应该足够好了吧?

所以point.getThis().getClass().getMethod(point.getSignature().getName(), ???) 我如何获得 Class paramaterTypes?

【问题讨论】:

    标签: java spring aop spring-aop http-method


    【解决方案1】:

    以下代码获取所需的控制器方法注释详细信息

        @Before("isRestController()")
    public void handlePost(JoinPoint point) {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
    
        // controller method annotations of type @RequestMapping
        RequestMapping[] reqMappingAnnotations = method
                .getAnnotationsByType(org.springframework.web.bind.annotation.RequestMapping.class);
        for (RequestMapping annotation : reqMappingAnnotations) {
            System.out.println(annotation.toString());
            for (RequestMethod reqMethod : annotation.method()) {
                System.out.println(reqMethod.name());
            }
        }
    
        // for specific handler methods ( @GetMapping , @PostMapping)
        Annotation[] annos = method.getDeclaredAnnotations();
        for (Annotation anno : annos) {
            if (anno.annotationType()
                    .isAnnotationPresent(org.springframework.web.bind.annotation.RequestMapping.class)) {
                reqMappingAnnotations = anno.annotationType()
                        .getAnnotationsByType(org.springframework.web.bind.annotation.RequestMapping.class);
                for (RequestMapping annotation : reqMappingAnnotations) {
                    System.out.println(annotation.toString());
                    for (RequestMethod reqMethod : annotation.method()) {
                        System.out.println(reqMethod.name());
                    }
                }
            }
        }
    }
    

    注意:此代码可以进一步优化。分享为一个例子来展示可能性

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-03
      • 2019-02-04
      • 1970-01-01
      • 1970-01-01
      • 2017-11-22
      • 1970-01-01
      相关资源
      最近更新 更多