如何以编程方式读取休息服务的路径?

How to programmatically read the path of a rest service?

假设我定义了以下简单的休息:

@RequestMapping("/user/data")
@ResponseBody
public String getUserDetails(@RequestParam int id) {
    ...
}

有没有办法通过代码的另一部分(即完全不同的方法)读取路径字符串? 类似于:

String restPath = SomeReflection.getPath("getuserdetails"); // received value: "/user/data"

WDYT? 谢谢!

已解决! 这是我需要的实现:

public String getUrlFromRestMethod(Class controllerClass, String methodName) {

        try {
            Method method = controllerClass.getMethod(methodName);
            if (method != null && method.isAnnotationPresent(RequestMapping.class)) {

                RequestMapping requestMappingAnnotation = method.getAnnotation(RequestMapping.class);
                return requestMappingAnnotation.toString();
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();//TODO
        }

        return null;
    }

我建议您在方法中添加一个 HttpServletRequest 请求,然后从那里开始 request.getServletPath()

ei

public String getUserDetails(HttpServletRequest request, @RequestParam int id) {

或者如果在 Spring http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#mvc-ann-requestmapping

中完成
@RequestMapping(path = "/{day}", method = RequestMethod.GET)
public Map<String, Appointment> getForDay(@PathVariable @DateTimeFormat(iso=ISO.DATE) Date day, Model model) {
    return appointmentBook.getAppointmentsForDay(day);
}
@RequestMapping(value="/owners/{ownerId}", method=RequestMethod.GET)  
public String findOwner(@PathVariable String ownerId, Model model) {  
  Owner owner = ownerService.findOwner(ownerId);    
  model.addAttribute("owner", owner);    
  return "displayOwner";   
}  

也许你可以调用它的值。

如果您的意思是您甚至想从另一个 class 以编程方式访问该值,那么也许您可以从这个示例开始制定您的解决方案:

    //get all methods defined in ClassA
    Method[] methods = ClassA.class.getMethods();
    for (Method m : methods) {
        //pick only the ones annotated with "@RequestMapping"
        if (m.isAnnotationPresent(RequestMapping.class)) {
            RequestMapping ta = m.getAnnotation(RequestMapping.class);
            System.out.println(ta.value()[0].toString());
        }
    }