SpringBoot——启动服务时获取所有controller层的接口url列表

需求

  在服务启动时,获取服务的所有controller层接口url列表,通过CommandLineRunner实现服务启动时的操作。

  1. CommandLineRunnerSpringApplication.run运行完成之后后才会运行自己创建的实现类。
  2. 加入@Component注解后,就可以将对象交给spring管理。
  3. 加入@Order()注解控制顺序,数字越小越靠前。

技术应用

  • CommandLineRunner
  • WebApplicationContext
  • RequestMappingHandlerMapping

CommandLineRunner源码

package org.springframework.boot;

@FunctionalInterface
public interface CommandLineRunner {
    void run(String... args) throws Exception;
}
  1. CommandLineRunner是一个接口,我们可以自定义实现该接口,并具体实现run方法。
  2. 如果在上下文中,若有多个实现该接口的类,就需要通过@Order注解进行加载顺序的指定。

代码模板

@Slf4j
@Component
@Order(1)
@RequiredArgsConstructor
public class CommandLineInitResource implements CommandLineRunner {

    /**
     * 上下文
     */
    @Autowired
    WebApplicationContext applicationContext;

	   @Value("${route.prefix}")
	   private String routePrefix;

    @Override
    public void run(String... args) throws Exception {

        //获取controller相关bean
        RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
        //获取method
        Map<RequestMappingInfo, HandlerMethod> methodMap = mapping.getHandlerMethods();
        //构造url list
        List<String> urlList = new ArrayList<>();
        //获取methodMap的key集合
        for (RequestMappingInfo info : methodMap.keySet()) {
            //controller url集合
            Set<String> urlSet = info.getPatternsCondition().getPatterns();
            //controller url拼接路由前缀
            urlList.addAll(urlSet.stream().map(url ->
                    //校验前缀
                    routePrefix.startsWith("/") ? (routePrefix + url) : ("/" + routePrefix + url)
            ).collect(Collectors.toList()));
			//获取所有方法类型
			//Set<RequestMethod> methodSet = info.getMethodsCondition().getMethods();
        }
        log.info("web controller urlList: {}", urlList);
    
    }
}
posted @ 2023-03-07 13:52  Andya_net  阅读(1226)  评论(0编辑  收藏  举报  来源