使用SpringBoot獲取所有接口的路由

SpringBoot獲取所有接口的路由

@Autowired
    WebApplicationContext applicationContext;
 
    @RequestMapping(value = "v1/getAllUrl", method = RequestMethod.POST)
    public Object getAllUrl() {
        RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
        // 獲取url與類和方法的對應信息
        Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
        
//      List<String> urlList = new ArrayList<>();
//      for (RequestMappingInfo info : map.keySet()) {
//          // 獲取url的Set集合,一個方法可能對應多個url
//          Set<String> patterns = info.getPatternsCondition().getPatterns();
//
//          for (String url : patterns) {
//              urlList.add(url);
//          }
//      }
 
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        for (Entry<RequestMappingInfo, HandlerMethod> m : map.entrySet()) {
            Map<String, String> map1 = new HashMap<String, String>();
            RequestMappingInfo info = m.getKey();  
            HandlerMethod method = m.getValue();  
            PatternsRequestCondition p = info.getPatternsCondition();  
            for (String url : p.getPatterns()) {  
                map1.put("url", url);
            }  
            map1.put("className", method.getMethod().getDeclaringClass().getName()); // 類名  
            map1.put("method", method.getMethod().getName()); // 方法名 
            RequestMethodsRequestCondition methodsCondition = info.getMethodsCondition();
            for (RequestMethod requestMethod : methodsCondition.getMethods()) {
                map1.put("type", requestMethod.toString());
            }
            
            list.add(map1);
        }

Springboot部分路由生效

問題記錄

項目新增接口”foo”,始終不生效,經排查發現controller層的@RequestMaping(value=“test”)統一加瞭基礎路徑”test”,我新增的接口註解為@PostMappinp(“test/foo),導致生成的路由為”test/test/foo”, 調用地址為”test/foo”,所以報瞭404。

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: