Sometimes you want to declare Filters as @Beans in order to have them managed and dependencies injected etc. but do not want them to be automatically registered.
This can be a problem particularly when working with Spring Security. Though this will apply in any situation with multiple filter chains.
Currently you have to declare a FilterRegistrationBean for every filter with setEnabled(false), which can get very tedious and can be a maintenance problem.
I propose a new annotation-based method to exempt filter beans from autoregistration. For maximum utility, perhaps by implementing FilterRegistrationBean (or just RegistrationBean) wholly as an annotation?
@Bean
@FilterRegistration(enabled=false)
public Filter manualFilter() { ... }
@Bean
@FilterRegistration(order=200, urlPatterns={"/path/**"})
public Filter automaticFilter() { ... }
Related: #2173
Having a dedicated annotation just to disable the bean wouldn't be great, but I quite like the idea of offering all the FilterRegistrationBean properties in the annotation. I could see that being quite useful. I do wonder how many people are registering custom filters.
@OrangeDog how many filters are you typically registering in your application? I'm trying to think about how we balance the amount of boilerplate needed with FilterRegistrationBean vs the additional overhead of introducing a new annotation for people to learn.
Right now just configuring spring-security-saml2-core involves nine filters, all of which are supposed to be beans, and none of which should go in the default filter chain. That's ~60 lines of FilterRegistrationBean declarations in order to turn them off.
I'm likely to add a couple more security filters at some point for additional authentication methods, e.g. persistent API tokens.
I've also faced this situation in a few projects, most of the times in the very same scenario as @OrangeDog's:
Filters as @Bean to leverage DIHaving FilterRegistrationBean properties exposed in annotation would be very helpful there. This shouldn't be an uncommon use case.
We have a messy dependencies, so filters by automatically registery is a risk for us, because it's not under control with filter list (they are register to application context already).
So we skipped all of subclasses for javax.servlet.Filter when scanning packages, use custom TypeFilter, but i don't think it's a good idea.
Is there a better way to resolve this?
Most helpful comment
Right now just configuring
spring-security-saml2-coreinvolves nine filters, all of which are supposed to be beans, and none of which should go in the default filter chain. That's ~60 lines ofFilterRegistrationBeandeclarations in order to turn them off.I'm likely to add a couple more security filters at some point for additional authentication methods, e.g. persistent API tokens.