Get HTTP Method from a joinPoint

前端 未结 1 1915
轻奢々
轻奢々 2021-01-29 05:02

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)          


        
相关标签:
1条回答
  • 2021-01-29 05:34

    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

    0 讨论(0)
提交回复
热议问题