欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-06-17 13:04:07
...

简介

controller类里的方法前@RequestMapping注释的路由信息获取,如下图所示 打印spring boot的controller里定义的路由

相关代码

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的controller里定义的路由

设计要点

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

参考链接

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

查看原文:http://www.huuinn.com/archives/195
更多技术干货:风匀坊
关注公众号:风匀坊