简体   繁体   English

读取 RequestMapping 注释值

[英]Read RequestMapping annotation value

To be able to do stats per endpoint, I want to be able to get the @RequestMapping annotation value, the parameterized version.为了能够对每个端点进行统计,我希望能够获得 @RequestMapping 注释值,即参数化版本。 My monitoring tool otherwise will consider different ids as different urls:否则,我的监控工具会将不同的 id 视为不同的 url:

@RequestMapping(value = "/customers/{customerId}/items/{itemId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
  public ResponseEntity<ItemDetailsDto> getItemById(
      @PathVariable(value = "customerId") int customerId
      @PathVariable(value = "itemId") int itemId)
      throws Exception
  {
    //do stuff

    //I want this to be "/customers/{customerId}/items/{itemId}"
    //,not "/customers/15988/items/85"
    String s = ????
  }

How can I grab /customers/{customerId}/items/{itemId} at runtime?如何在运行时获取/customers/{customerId}/items/{itemId} My tool allows me to intercept methods and capture its parameters, so I could also monitor a specific method in the Spring framework to catch the setting or getting of something for example.我的工具允许我拦截方法并捕获其参数,因此我还可以监视 Spring 框架中的特定方法以捕获例如设置或获取某些内容。

You can use Java reflection to do so, you just need to do like this:你可以使用Java反射来做到这一点,你只需要这样做:

String s= this.getClass().getDeclaredMethod("getItemById", int.class, int.class).getAnnotation(RequestMapping.class).value();

For the getDeclaredMethod the first parameter is the name of method and the other parameters are the parameters' types of that method.对于getDeclaredMethod ,第一个参数是方法的名称,其他参数是该方法的参数类型。

Another approach will be另一种方法是

private static final String URI_GET_ITEM_BY_ID ="/customers/{customerId}/items/{itemId}";

@RequestMapping(value = URI_GET_ITEM_BY_ID, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
  public ResponseEntity<ItemDetailsDto> getItemById(
      @PathVariable(value = "customerId") int customerId
      @PathVariable(value = "itemId") int itemId)
      throws Exception
  {
    //do stuff

    // Use URI_GET_ITEM_BY_ID

  }

Update 1:更新 1:

Assuming the controller is annotated with @RestController假设控制器用@RestController注释

@RestController
public class SampleController {

      @RequestMapping(value = "/customers/{customerId}/items/{itemId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
  public ResponseEntity<ItemDetailsDto> getItemById(
      @PathVariable(value = "customerId") int customerId
      @PathVariable(value = "itemId") int itemId)
      throws Exception
  {
    //do stuff

    //I want this to be "/customers/{customerId}/items/{itemId}"
    //,not "/customers/15988/items/85"
    String s = ????
  }

}

following Aspect can be used to get the URI path without altering the controller methods.以下Aspect可用于在不更改控制器方法的情况下获取 URI 路径。

@Aspect
@Component
public class RestControllerAspect {

    @Pointcut("@within(org.springframework.web.bind.annotation.RestController) && within(rg.boot.web.controller.*)")
    public void isRestController() {

    }

    @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(String val : annotation.value()) {
                System.out.println(val);
            }
        }

    }
}

This would print这将打印

@org.springframework.web.bind.annotation.RequestMapping(path=[], headers=[], method=[GET], name=, produces=[application/json], params=[], value=[/customers/{customerId}/items/{itemId}], consumes=[])
/customers/{customerId}/items/{itemId}

for a request to URI : /customers/1234/items/5678对于对 URI 的请求: /customers/1234/items/5678

Update 2:更新 2:

Another way is to import另一种方式是导入

import static org.springframework.web.servlet.HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE;
import org.springframework.web.context.request.RequestContextHolder;

and get the path using the following code并使用以下代码获取路径

 RequestAttributes reqAttributes = RequestContextHolder.currentRequestAttributes(); 
 String s = reqAttributes.getAttribute(BEST_MATCHING_PATTERN_ATTRIBUTE, 0);

This is adapted from my answer to another question.这是改编自我回答另一个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM