如何在 Spring MVC 中找到所有控制器? [英] How to find all controllers in Spring MVC?

查看:35
本文介绍了如何在 Spring MVC 中找到所有控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了提供一些运行时生成的 API 文档,我想遍历所有 Spring MVC 控制器.所有控制器都使用 Spring @Controller 注释进行注释.目前我这样做:

To provide some runtime generated API documentation I want to iterate over all Spring MVC controllers. All controllers are annotated with the Spring @Controller annotation. Currently I do it like this:

for (final Object bean: this.context.getBeansWithAnnotation(
        Controller.class).values())
{
    ...Generate controller documentation for the bean...
}

但是此代码的第一次调用极其慢.我想知道 Spring 是否会遍历类路径中的 ALL 类,而不仅仅是检查定义的 bean.当上面的代码运行时,控制器已经加载,日志显示所有它们及其请求映射,所以 Spring MVC 必须已经知道它们,并且必须有一种更快的方法来获取它们的列表.但是如何?

But the first call of this code is EXTREMELY slow. I wonder if Spring iterates over ALL classes in the classpath instead of just checking the defined beans. The controllers are already loaded when the above code is run, the log displays all of them with their request mappings so Spring MVC must already know them all and there must be a faster way to get a list of them. But how?

推荐答案

几个月前我也遇到过这样的需求,我使用以下代码片段实现了它.

I have also came across such requirement before some months and I have achieved it using the following code snippet.

ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
        scanner.addIncludeFilter(new AnnotationTypeFilter(Controller.class));
        for (BeanDefinition beanDefinition : scanner.findCandidateComponents("com.xxx.yyy.controllers")){
            System.out.println(beanDefinition.getBeanClassName());
        }

您也可以使用控制器执行类似操作.

You can also do something like this with your controllers.

更新了代码片段.删除了不必要的代码,只显示控制器的类名以便更好地理解.希望这对你有帮助.干杯.

Updated the code snippet. Removed the not necessary code and just displaying the class name of the controllers for better understanding. Hope this helps you. Cheers.

这篇关于如何在 Spring MVC 中找到所有控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆