spring - Control @RestController availability programatically -
is possible control @restcontroller
programatically enable or disable it? don't want write code in each @requestmapping
method kind of if (!enabled) { return 404exception; }
i've seen this question works @ startup time. need allow me enable or disable controller multiple times.
i've thought of different ways don't know doable in spring.
- actually control container (jetty in case) requests particular endpoint disabled
- somehow control
requestmappinghandlermapping
since seems class mapping between urls , controllers - control lifecycle of
@restcontroller
component can create , destroy @ will, i'm not sure how trigger mapping endpoint
if end result want respond 404 when decide specific endpoint should disabled write interceptor checks whether enabled condition false and, if so, sets response accordingly.
for example:
@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 have mechanism of inferring or discovering whether // endpoint represented requesturi should allowed or disallowed return ...; } }
in spring boot, registering own interceptor involves implementing webmvcconfigureradapter
. example:
@configuration public class customwebmvcconfigurer extends webmvcconfigureradapter { @autowired private handlerinterceptor conditionalrejectioninterceptor; @override public void addinterceptors(interceptorregistry registry) { // can use .addpathpatterns(...) here limit interceptor specific endpoints // used replace 'conditional on value of requesturi' code in interceptor registry.addinterceptor(conditionalrejectioninterceptor); } }
wiki
Comments
Post a Comment