Prevent Spring Boot from registering a servlet filter

后端 未结 2 988
天命终不由人
天命终不由人 2020-11-30 01:27

I have a Spring Boot WebMVC application, and a bean that inherits from AbstractPreAuthenticatedProcessingFilter which I am explicitly adding to a specific spot in the Spring

相关标签:
2条回答
  • 2020-11-30 01:45

    By default Spring Boot creates a FilterRegistrationBean for every Filter in the application context for which a FilterRegistrationBean doesn't already exist. This allows you to take control of the registration process, including disabling registration, by declaring your own FilterRegistrationBean for the Filter. For your PreAuthenticationFilter the required configuration would look like this:

    @Bean
    public FilterRegistrationBean registration(PreAuthenticationFilter filter) {
        FilterRegistrationBean registration = new FilterRegistrationBean(filter);
        registration.setEnabled(false);
        return registration;
    }
    

    You may also be interested in this Spring Boot issue which discusses how to disable the automatic registration of Filter and Servlet beans.

    0 讨论(0)
  • 2020-11-30 01:49

    If you want to unregister all filters at one time here's my trick:

    public class DefaultFiltersBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
    
        @Override
        public void postProcessBeanFactory(ConfigurableListableBeanFactory bf)
                throws BeansException {
            DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) bf;
    
            Arrays.stream(beanFactory.getBeanNamesForType(javax.servlet.Filter.class))
                    .forEach(name -> {
    
                        BeanDefinition definition = BeanDefinitionBuilder
                                .genericBeanDefinition(FilterRegistrationBean.class)
                                .setScope(BeanDefinition.SCOPE_SINGLETON)
                                .addConstructorArgReference(name)
                                .addConstructorArgValue(new ServletRegistrationBean[]{})
                                .addPropertyValue("enabled", false)
                                .getBeanDefinition();
    
                        beanFactory.registerBeanDefinition(name + "FilterRegistrationBean",
                                definition);
                    });
        }
    }
    

    A bit more about this technique - here.

    0 讨论(0)
提交回复
热议问题