Spring controller的url扫描

spring rest项目url规范

用到很多的url,有的不符合规范,需要统计所有url查看哪些不合理,哪些需要改进的。就写了一个小程序来读取Controller的注解来分析rest所用到的url。

package com.*.*.restapi.common;

import org.springframework.web.bind.annotation.RequestMapping;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;

/**
 * @author dongbin.yu
 * @version 1.0.0
 * @since 2015/10/21
 */
public class RequestMappingUtil {

    private static String controllerUrl = "com.*.restapi.controller";

    public static void main(String[] args){
        URL resource = RequestMappingUtil.class.getClass().getResource("/" + controllerUrl.replace('.','/'));

        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

        File directory = new File(resource.getPath());
        if(directory.isDirectory()){
            File[] files = directory.listFiles();
            for (File file : files) {
                if(file.isDirectory()){
                    File[] files1 = file.listFiles();
                    for (File file1 : files1) {
                        exportUrl(file1,"." + file.getName());
                    }
                } else {
                    exportUrl(file,"");
                }

            }

        }

    }

    public static void exportUrl(File file,String name){
        try {
            String fileName = file.getName();
            Class<?> clazz = Class.forName(controllerUrl + name + "." + fileName.substring(0, fileName.indexOf(".")));
            RequestMapping requestMapping = clazz.getAnnotation(RequestMapping.class);

            String topUrl = "";
            if(requestMapping != null){
                topUrl = requestMapping.value()[0];
            }

            Method[] methods = clazz.getMethods();
            for (Method method : methods) {
                RequestMapping annotation = method.getAnnotation(RequestMapping.class);
                if(annotation != null){
                    String methodUrl = annotation.value()[0];

                    if(methodUrl.startsWith("/")){
                        System.out.println(topUrl + methodUrl + ":" + (annotation.method().length == 0 ? "GET" : annotation.method()[0]));
                    } else {
                        System.out.println(topUrl + "/" + methodUrl + ":" + (annotation.method().length == 0 ? "GET" : annotation.method()[0]));
                    }
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

分析后的结果

通过读取RequestMapping注解和method注解,读取的时候要注意是否在Class头上有前缀。还有是否有层级嵌套。

attributionReport/getAttributionPathList:POST

调用后发现RequestMapping的value和method都是数组,可以接受多个参数的。





你可能感兴趣的:(spring,REST,url)