14

ランタイムで生成された API ドキュメントを提供するために、すべての Spring MVC コントローラーを反復処理したいと考えています。すべてのコントローラーには、Spring @Controller アノテーションが付けられます。現在、私は次のようにしています:

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

しかし、このコードの最初の呼び出しは非常に遅いです。定義された Bean をチェックするだけでなく、Spring がクラスパス内のすべてのクラスを反復するのではないかと思います。上記のコードが実行されると、コントローラーはすでにロードされており、ログにはそれらすべてがリクエストマッピングとともに表示されるため、Spring MVC はそれらすべてを既に認識している必要があり、それらのリストを取得するためのより高速な方法が必要です。しかし、どのように?

4

2 に答える 2

37

@Japsが提案するアプローチが好きですが、別のアプローチもお勧めしたいと思います。これは、クラスパスがSpringによって既にスキャンされており、コントローラーと要求がマップされたメソッドが構成されているという観察に基づいています。このマッピングはhandlerMappingコンポーネントで維持されます。Spring 3.1を使用している場合、このhandlerMappingコンポーネントはRequestMappingHandlerMappingのインスタンスであり、これらの行に沿って、handlerMappedMethodsと関連するコントローラーを見つけるためにクエリを実行できます(古いバージョンのSpringを使用している場合は、同様のアプローチを使用できるはずです)。 )::

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

@Controller
public class EndpointDocController {
 private final RequestMappingHandlerMapping handlerMapping;
 
 @Autowired
 public EndpointDocController(RequestMappingHandlerMapping handlerMapping) {
  this.handlerMapping = handlerMapping;
 }
  
 @RequestMapping(value="/endpointdoc", method=RequestMethod.GET)
 public void show(Model model) {
  model.addAttribute("handlerMethods", this.handlerMapping.getHandlerMethods());
 } 
}

これについての詳細は、このURLhttp ://biju-allandsundry.blogspot.com/2012/03/endpoint-documentation-controller-for.htmlで提供しています。

これは、SpringSourceのRossenStoyanchevによるSpring3.1に関するプレゼンテーションに基づいています。

于 2012-06-05T14:22:31.043 に答える
17

また、数か月前にそのような要件に遭遇し、次のコード スニペットを使用してそれを達成しました。

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());
        }

コントローラーでこのようなことを行うこともできます。

コード スニペットを更新しました。不要なコードを削除し、理解を深めるためにコントローラーのクラス名を表示するだけにしました。これがお役に立てば幸いです。乾杯。

于 2012-06-05T13:23:02.913 に答える