3
5

More than 3 years have passed since last update.

Spring BootのHandlerInterceptorで実行されるControllerのクラス名やメソッド名を取得する

Posted at
1. やりたいこと
  • HandlerInterceptorで実行されるControllerのクラス名やメソッド名を取得する
  • 2. バージョンや条件など
  • Spring Boot 2.1.7.RELEASE
  • 3. やったこと
    DemoInterceptor.java
    public class DemoInterceptor extends HandlerInterceptorAdapter {
        @Override
        public boolean preHandle(HttpServletRequest request,
                                 HttpServletResponse response,
                                 Object handler) throws Exception {
            // (1) HandlerMethodでない場合スキップ
            // jsとかだとorg.springframework.web.servlet.resource.ResourceHttpRequestHandlerになる
            if (!HandlerMethod.class.isInstance(handler)) {
                return true;
            // (2) handlerをHandlerMethodにcastする
            HandlerMethod handlerMethod = HandlerMethod.class.cast(handler);
            // (3) 実行されるControllerのクラス名
            String beanTypeName = handlerMethod.getBeanType().getName();
            // (4) 実行されるメソッドのメソッド名
            String methodName = handlerMethod.getMethod().getName();
            // (5) ショートログメッセージ
            // 以下のようにFQCN#MethodName[Arguments]が取得できる
            // [example]
            // case1) No arguments
            // jp.gr.java_conf.pekokun.web.app.HelloController#say[0 args]
            // case2) 1 argument
            // jp.gr.java_conf.pekokun.web.app.HelloController#say[1 args]
            String shortLogMessage = handlerMethod.getShortLogMessage();
            // (6) メソッドのパラメータの情報も取得できる
            // handlerMethod.getMethodParameters()...
            return super.preHandle(request, response, handler);
    

    Register as a new user and use Qiita more conveniently

    1. You get articles that match your needs
    2. You can efficiently read back useful information
    What you can do with signing up
    5