2017-08-23 5 views
3

@RestControllerをプログラムで有効にするか無効にすることはできますか?私はちょうど各@RequestMappingの方法でコードを書くことはしませんif (!enabled) { return 404Exception; }プログラムで制御可能@RestControllerの可用性

私はthis questionを見ましたが、起動時にのみ動作します。私が必要とするのは、コントローラを複数回有効または無効にすることができるものです。

私はさまざまな考え方をしていますが、どちらが春にできるかはわかりません。

  1. 実際にその特定のエンドポイントへの要求は、制御
  2. URLとコントローラ間のマッピングを行い、そのクラスのようですので、
  3. はどういうわけかRequestMappingHandlerMappingを制御無効になっているので、(私の場合は桟橋)コンテナを制御します@RestControllerコンポーネントのライフサイクル私はそれを作成し、意志でそれを破壊するが、最終結果はあなたがで応答したいということであれば、私は、エンドポイント
+0

'if(!enabled)'ロジックは、 'RequestMappingHandlerMapping'のカスタム実装よりもはるかに簡単です。 Togglzのようなトグル機能のフレームワークを見てください。 – nbrooks

+0

これはいかがですか? https://stackoverflow.com/questions/44456388/conditionalonexpression-on-a-class-object-getter –

+0

インターセプタ(URLパスベース)またはControllerAdvice(これはあなたが望むものに近いかもしれません) 。また、DispatcherServletからの突き刺しを開始することもできますが、私はそのb4を試みたことがありません。 – hummingV

答えて

1

へのマッピングをトリガーするかどうかはわかりませんができるようにあなたが404特定のエンドポイントを無効にする必要があると判断した場合、有効な条件が偽であるかどうかをチェックするインターセプタを作成し、そうであればそれに応じてレスポンスを設定することができます。例えば

:春ブーツで

@Component 
public class ConditionalRejectionInterceptor extends HandlerInterceptorAdapter { 

    @Override 
    public boolean preHandle(HttpServletRequest request, 
      HttpServletResponse response, Object handler) throws Exception { 
     String requestUri = request.getRequestURI(); 
     if (shouldReject(requestUri)) { 
      response.setStatus(HttpStatus.NOT_FOUND.value()); 
      return false; 
     } 
     return super.preHandle(request, response, handler); 
    } 

    private boolean shouldReject(String requestUri) { 
     // presumably you have some mechanism of inferring or discovering whether 
     // the endpoint represented by requestUri should be allowed or disallowed 
     return ...; 
    } 
} 

、独自のインターセプタを登録するだけでWebMvcConfigurerAdapterを実装する必要。例:

@Configuration 
public class CustomWebMvcConfigurer extends WebMvcConfigurerAdapter { 

    @Autowired 
    private HandlerInterceptor conditionalRejectionInterceptor; 

    @Override 
    public void addInterceptors(InterceptorRegistry registry) { 
    // you can use .addPathPatterns(...) here to limit this interceptor to specific endpoints 
    // this could be used to replace any 'conditional on the value of requestUri' code in the interceptor 
    registry.addInterceptor(conditionalRejectionInterceptor); 
    } 
} 
+0

これはほぼ完全に機能しました。私は 'return false'を追加する必要がありました。そうでなければ要求はハンドラのチェーンの下で続きます – Hilikus

関連する問題