카테고리 없음

[봄] 모든 컨트롤러의 모든 요청 매핑을 얻는 방법은 무엇입니까?

필살기쓰세요 2021. 1. 21. 05:09

Google GuavaJava Reflection API 를 사용하여이를 달성 할 수 있습니다 .

<dependency>
  <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
      <version>19.0</version>
      </dependency>
      

Google Guava 에는 최상위 클래스를 검색하는 세 가지 메서드가있는 ClassPath 클래스가 포함되어 있습니다.getTopLevelClasses(String packageName)

이 예제 코드를 참조하십시오.

public void getClassOfPackage(String packagenom) {

    final ClassLoader loader = Thread.currentThread()
                .getContextClassLoader();
                    try {
                    
                            ClassPath classpath = ClassPath.from(loader); // scans the class path used by classloader
                                    for (ClassPath.ClassInfo classInfo : classpath.getTopLevelClasses(packagenom)) {
                                             if(!classInfo.getSimpleName().endsWith("_")){
                                                         System.out.println(classInfo.getSimpleName());
                                                                     }
                                                                             }
                                                                                 } catch (IOException e) {
                                                                                         e.printStackTrace();
                                                                                             }
                                                                                             
                                                                                             }
                                                                                             

아래 코드는 단일 컨트롤러 에서 모든 @RequestMapping을 인쇄하므로이 코드를 업데이트 할 수 있습니다.

 Class clazz = Class.forName("com.abc.cbe.rest.controller.MyController"); // or list of controllers, //you can iterate that list
    for(Method method :clazz.getMethods()){
             for(Annotation annotation :method.getDeclaredAnnotations()){
                          if(annotation.toString().contains("RequestMapping"))
                                      System.out.println("Annotation is..."+ annotation.toString());
                                           }
                                                }
                                                


출처
https://stackoverflow.com/questions/39916987