打印spring boot的controller里定义的路由

简介

controller类里的方法前@RequestMapping注释的路由信息获取,如下图所示

相关代码

RouteList.java

package com.ffan.util;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Arrays;
import java.util.Set;

public class RouteList {
    public static void main(String[] args) throws ClassNotFoundException {
        ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);

        scanner.addIncludeFilter(new AnnotationTypeFilter(Controller.class));

        Set<BeanDefinition> beanSet = scanner.findCandidateComponents("com.ffan.smartlife.controller");

        for (BeanDefinition def : beanSet) {
            Class<?> clazz = Class.forName(def.getBeanClassName());
            Arrays.stream(clazz.getDeclaredMethods()).map(m -> m.getAnnotation(RequestMapping.class)).filter(
                    a -> a != null && a.value().length > 0).forEach(
                    a -> Arrays.stream(a.value()).forEach(
                            p -> {
                                System.out.println(p);
                            }
                    ));
        }
    }
}

效果图

spring boot route list

设计要点

  • 通过ClassPathScanningCandidateComponentProvider获取spring boot框架的元数据
  • 获取controller信息
  • 获取controller里的注解RequestMapping信息

参考链接

https://qiita.com/shigeshibu44/items/886efb44c8c573c3ba6b

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注