Java反射获取所有Controller和RestController类的方法

Java反射获取所有Controller和RestController类的方法

引入三方反射工具Reflections

<dependency>
    <groupId>org.reflectionsgroupId>
    <artifactId>reflectionsartifactId>
    <version>0.10.2version>
dependency>

利用反射获取指定包下的Controller类


public class ControllerClassHolder {
    public static final Reflections REFLECTION = new Reflections("com.example.controller");
    
    public static final Set<Class<?>> CLASSES;
    
    static {
        CLASSES = REFLECTION.getTypesAnnotatedWith(Controller.class);
        CLASSES.addAll(REFLECTION.getTypesAnnotatedWith(RestController.class);)
    }
}

获取Controller方法

每个http请求基本都会使用@RequestMapping注解

List<Method> methods = new ArrayList<>();

for (Class<?> controllerClass : CLASSES) {
    Method[] declaredMethods = controllerClass.getDeclaredMethods();
    Set<Method> methods = Arrays.stream(declaredMethods)
        .filter(m -> m.getAnnotation(RequestMapping.class) != null)
        .collect(Collectors.toSet());
}

你可能感兴趣的:(Java小工具,spring,boot,java,spring,后端,mvc)