Search code examples
javaspring-bootfeature-flags

Enable/Disable all controllers of spring boot app?


I'm wondering if there is any pattern or implementation that allows me to enable/disable all the controllers at once of a given spring boot application by using a simple boolean variable that was provided by another feature flags service.

I'm thinking of putting a conditional check in each of the controller paths but it's a really bad way of doing it.

Thanks in advance


Solution

  • You can define custom Filter and register that. Sample Filter code at.

    public class RequestAllowDenyFilter implements Filter {
    
        private boolean isAllowed = true;
    
        public RequestAllowDenyFilter(boolean isAllowed) {
            this.isAllowed = isAllowed;
        }
    
        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                throws IOException, ServletException {
            if (isAllowed) {
                chain.doFilter(request, response);
            } else {
                ((HttpServletResponse) response).setStatus(HttpStatus.SERVICE_UNAVAILABLE.value());
            }
        }
    
    }
    

    Then when you register filter you need to pass do you want to allow/deny request.

    @Value("${request.enabled:true}")
    private boolean isEnabled;
    
    @Bean
    public FilterRegistrationBean<RequestAllowDenyFilter> loggingFilter() {
        FilterRegistrationBean<RequestAllowDenyFilter> registrationBean
          = new FilterRegistrationBean<>();
    
        registrationBean.setFilter(new RequestAllowDenyFilter(isEnabled));
        registrationBean.addUrlPatterns("/**");
        registrationBean.setOrder(0);
    
        return registrationBean;
    }
    

    You need to define request.enabled in application.properties file. Either true/false based on what you want to do.