从joinPoint获取HTTP方法

问题描述 投票:0回答:1

我需要从一个方面的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个回答
0
投票

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

    @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());
                }
            }
        }
    }
}

注意:此代码可以进一步优化。以示例为例,以演示可能性

© www.soinside.com 2019 - 2024. All rights reserved.