如何在Spring Boot中添加过滤器类?

问题描述:

Spring Boot中的 Filter 类(对于Web应用程序)是否有任何注释?也许 @Filter ?

Is there any annotation for a Filter class (for web applications) in Spring Boot? Perhaps @Filter?

我想在我的项目中添加一个自定义过滤器.

I want to add a custom filter in my project.

Spring Boot参考指南关于 FilterRegistrationBean ,但是我不确定如何使用它.

The Spring Boot Reference Guide mentioned about FilterRegistrationBean, but I am not sure how to use it.

如果要设置第三方过滤器,可以使用 FilterRegistrationBean .

If you want to setup a third-party filter you can use FilterRegistrationBean.

例如,等同于 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>

这将是您的 @Configuration 文件中的两个bean:

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();
}

以上内容已通过Spring Boot 1.2.3进行了测试.

The above was tested with Spring Boot 1.2.3.