I wonder, if there is any annotation for a Filter
class (for web applications) in Spring Boot? Perhaps @Filter
?
I want to add a custom filter in my project.
The Spring Boot Reference Guide mentioned about
FilterRegistrationBean
, but I am not sure how to use it.
If you want to setup a third-party filter you can use FilterRegistrationBean
.
For example the equivalent of web.xml
<filter>
<filter-name>SomeFilter</filter-name>
<filter-class>com.somecompany.SomeFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SomeFilter</filter-name>
<url-pattern>/url/*</url-pattern>
<init-param>
<param-name>paramName</param-name>
<param-value>paramValue</param-value>
</init-param>
</filter-mapping>
These will be the two beans in your @Configuration
file
@Bean
public FilterRegistrationBean someFilterRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(someFilter());
registration.addUrlPatterns("/url/*");
registration.addInitParameter("paramName", "paramValue");
registration.setName("someFilter");
registration.setOrder(1);
return registration;
}
public Filter someFilter() {
return new SomeFilter();
}
The above was tested with spring-boot 1.2.3