简体   繁体   中英

How do I manually register filters in springboot?

I have three Filter class: AFilter、BFilter、CFilter,and attempt to register them by the following code:

@Component
public class DefaultFilterRegister implements BeanDefinitionRegistryPostProcessor {

    //......

    private List<Filter> toRegister = FilterUtils.getInitFilters();

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        if (CollectionUtils.isEmpty(toRegister)) {
            return;
        }
        for (Filter filter : toRegister) {

            BeanDefinitionBuilder beanDefinitionBuilder =
                    BeanDefinitionBuilder.genericBeanDefinition(filter.getClass());

            AbstractBeanDefinition rawBeanDefinition = beanDefinitionBuilder.getRawBeanDefinition();

            rawBeanDefinition.setAutowireMode(GenericBeanDefinition.AUTOWIRE_BY_TYPE);

            registry.registerBeanDefinition(filter.getClass().getName(), rawBeanDefinition);
        }
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

    }
    
    //......

}

They had been register to beanfactory, but they are not filters. How can I turn them into filters?

My main goal is to make the built-in filters and user-defined filters orderable. Using the above example of AFilter, BFilter, and CFilter, these three are system built-in, and when the user wants to add a DFilter, I can provide something like addFilterBefore() to make the filter order A, D, B, C.

You can return the below bean in your web security configuration to register the filter. Like below example.

@Bean 
public FilterRegistrationBean<CustomFilter> restRegistrationBean() {   
      FilterRegistrationBean<CustomFilter> filterRegistrationBean = new FilterRegistrationBean<>();
      filterRegistrationBean.setFilter(customFilterObject);
      filterRegistrationBean.addUrlPatterns("/mapping1","/mapping2"); 
      return filterRegistrationBean; 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM