Sk Monjurul Haque
Sk Monjurul Haque

Reputation: 145

what is the significance of @Component annotation for Filter in spring boot?

Why do we need to use @Component annotation for Filter in spring boot, why we can't use @Configuration annotation.

Please note: I am not trying to register filter in FilterRegistrationBean.

Upvotes: 1

Views: 764

Answers (1)

Andy Wilkinson
Andy Wilkinson

Reputation: 116061

@Configuration indicates that the class may contain @Bean methods and should be processed to define those beans in the application context. This isn't something that a Filter does so it should not be annotated with @Configuration.

If you look at the source for @Configuration, you'll see that it's annotated with @Component. @Configuration is a special kinds of @Component. In this case, all you need is for the Filter itself to be a bean. It doesn't have any @Bean methods so it's sufficient for it to be annotated with @Component. This will ensure that the Filter is a bean and Spring Boot will the register the Filter bean with the servlet container without any need for a FilterRegistrationBean and without wasting resources unnecessarily processing your Filter's class looking for @Bean methods.

Upvotes: 7

Related Questions