扫描springboot项目某个包下的全部接口(用RequestMapping注解标注的)

50 阅读1分钟

import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.core.annotation.MergedAnnotation;
import org.springframework.core.annotation.MergedAnnotations;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;


public class InterfaceScan {

    public static void main(String[] args) throws IOException, ClassNotFoundException {

        String basePackage = "com.ruoyi.web.controller.system";

        String replace = basePackage.replace(".", "/");

        ClassPathResource classPathResource = new ClassPathResource(replace);

        File[] files = classPathResource.getFile().listFiles();

        ClassLoader classLoader = ClassUtils.getDefaultClassLoader();

        for (File file : files) {
            String name = file.getName();
            int i = name.lastIndexOf(".");
            name = name.substring(0,i);
            Class<?> clazz = ClassUtils.forName(basePackage + "." + name, classLoader);
            RequestMapping requestMapping = clazz.getAnnotation(RequestMapping.class);
            String requestRoot = "";
            if(requestMapping!=null){
                requestRoot = requestMapping.value()[0];
            }

            Method[] allDeclaredMethods = ReflectionUtils.getAllDeclaredMethods(clazz);

            for (Method allDeclaredMethod : allDeclaredMethods) {
                if(AnnotatedElementUtils.hasAnnotation(allDeclaredMethod,RequestMapping.class)){
                    MergedAnnotations from = MergedAnnotations.from(allDeclaredMethod);

                    MergedAnnotation<RequestMapping> annotation = from.get(RequestMapping.class);

                    RequestMapping synthesize = annotation.synthesize();

                    String[] value = synthesize.value();

                    RequestMethod[] method = synthesize.method();

                    String requestMethod = "";

                    if(method.length>0) {
                        requestMethod = method[0].name();
                    }


                    String s;

                    if(value.length>0){
                        s = requestRoot+value[0]+" requestMethod:"+requestMethod;
                    }else {
                        s= requestRoot+" requestMethod:"+requestMethod;;
                    }



                    System.out.println(s);

                }
            }
        }


    }
}

image.png

输出结果如下