Search code examples
javaspringaopspring-aophttp-method

Get HTTP Method from a joinPoint


I need to get the http method like POST/PATCH/GET/etc from a joinPoint in an aspect.

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

From point.getThis.getClass(), I get the the controller that this call is intercepted. Then if I get the method from it and then annotations. That should be good enough right?

So point.getThis().getClass().getMethod(point.getSignature().getName(), ???) How do i get Class paramaterTypes?


Solution

  • Following code gets the required controller method annotation details

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

    Note : This code can be further optimized. Shared as an example to demonstrate the possibilities