2017-01-12 7 views
0

Spring-MVCの@RequestMappingアノテーションには、各リソースを識別するためのパラメータ "name"があります。Spring-MVC:名前でマッピングの詳細を見つける

状況によっては、フライトでこの情報にアクセスする必要があります。マッピングの詳細(例:path)を特定の名前で取得する必要があります。

ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false); 
scanner.addIncludeFilter(new AnnotationTypeFilter(RequestMapping.class)); 
// ... find classes ... go through its methods ... 

しかし、それは非常に醜いです:私はこの注釈のクラスをスキャンを介して必要なインスタンスを取得することができます

確かに。それ以上の簡単な解決策はありますか?

答えて

3

RequestMappingHandlerMappingを使用してすべてのマッピングを取得し、名前に基づいてフィルタリングすることができます。次に、残りのapiを作成し、api /マッピングのパスの詳細を返すコードスニペットを示します。

import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.web.bind.annotation.GetMapping; 
import org.springframework.web.bind.annotation.PathVariable; 
import org.springframework.web.bind.annotation.RestController; 
import org.springframework.web.method.HandlerMethod; 
import org.springframework.web.servlet.mvc.method.RequestMappingInfo; 
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; 

@RestController 
public class EndpointController { 

    @Autowired 
    private RequestMappingHandlerMapping handlerMapping; 

    @GetMapping("endpoints/{name}") 
    public String show(@PathVariable("name") String name) { 
     String output = name + "Not Found"; 
     Map<RequestMappingInfo, HandlerMethod> methods = this.handlerMapping.getHandlerMethods(); 

     for (Map.Entry<RequestMappingInfo, HandlerMethod> entry : methods.entrySet()) { 
      if (entry.getKey().getName() != null && entry.getKey().getName().equals(name)) { 
       output = entry.getKey().getName() + " : " + entry.getKey(); 
       break; 
      } 
     } 
     return output; 
    } 
} 

上記は一例であり、あなたはとにかくあなたがそれをautowireできるまであなたが望むRequestMappingHandlerMappingを使用することができます。

+0

いいね、アイデアありがとう – Andremoniy

関連する問題