springboot獲取所有URL和swagger註解參數

1.簡介

   因爲做了RBAC結構的權限模型,又懶得寫管理界面,就直接一網打盡,寫一個獲取所有url路徑和swagger文檔註解的方法,然後百度了下,大部分都是隻獲取URL接口路徑,我拓展了下,可以加上方法的註解參數。

   swagger註解可以換成自定義的註解,很簡單的,註釋裏有體現。

2.代碼

    @Autowired
    private WebApplicationContext applicationContext;

    @RequestMapping(value = "getAllUrl")
    public Object getAllUrl() throws ClassNotFoundException {
        RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
        Map<RequestMappingInfo, HandlerMethod> mappingHandlerMethods = mapping.getHandlerMethods();

        List<UrlDesc> list = new ArrayList();

        for (Map.Entry<RequestMappingInfo, HandlerMethod> map : mappingHandlerMethods.entrySet()) {
            UrlDesc urlDesc = new UrlDesc();
            RequestMappingInfo info = map.getKey();
            HandlerMethod method = map.getValue();
            PatternsRequestCondition patternsCondition = info.getPatternsCondition();
            String className = method.getMethod().getDeclaringClass().getName();
            /**
             * 匹配包路徑 根據自己的路徑替換
             */
            if (className.contains("com.com.controller")) {
                //獲取類對象
                Class clazz = Class.forName(method.getMethod().getDeclaringClass().getName());
                String metName = method.getMethod().getName();
                /**
                 * 因爲單獨獲取一個類對象要指定參數,不適合批量使用,所以獲取所有的方法然後根據name篩選
                 */
                Method[] clazzDeclaredMethods = clazz.getDeclaredMethods();
                Arrays.stream(clazzDeclaredMethods).forEach(
                        c -> {
                            if(c.getName().equals(metName)){
                                /* swagger註解 可以換成別的 */
                                ApiOperation annotation = c.getAnnotation(ApiOperation.class);
                                if(null != annotation){
                                    urlDesc.setDesc(annotation.value());
                                }
                            }
                        }
                );
                for(String url : patternsCondition.getPatterns()) {
                    urlDesc.setUrl(url);
                }
                list.add(urlDesc);
            }
        }
        return list;
    }

實體類

@Data
public class UrlDesc implements Serializable,Cloneable {

    private static final long serialVersionUID = 1L;

    /**
     * 路徑
     */
    private String url;

    /**
     * 描述
     */
    private String desc;

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章