Prevent Spring Boot from registering a servlet filter

后端 未结 2 991
天命终不由人
天命终不由人 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: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.

提交回复
热议问题