欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring boot 配置Filter过滤器

程序员文章站 2022-04-28 16:41:40
...

 

1、通过 @WebFilter 注解来配置

@Component

@WebFilter(urlPatterns = "/webapi/*", filterName = "authFilter")

public class AuthFilter implements Filter {

......

}

 

 

2、通过 @Bean 注解来配置

我这个是写在带 @SpringBootApplication 注解的类里面的。

@Bean

public FilterRegistrationBean testFilterRegistration() {

FilterRegistrationBean registration = new FilterRegistrationBean(new TestFilter());

registration.addUrlPatterns("/webapi/*"); //

registration.addInitParameter("paramName", "paramValue"); //

registration.setName("testFilter");

return registration;

}

那如果有多个过虑器,怎么指定执行的顺序呢?

通过 registration.setOrder(1);  来设置,例如:

@Bean

public FilterRegistrationBean testFilterRegistration() {

FilterRegistrationBean registration = new FilterRegistrationBean(new TestFilter());

registration.addUrlPatterns("/webapi/*"); //

registration.addInitParameter("paramName", "paramValue"); //

registration.setName("testFilter");

registration.setOrder(1);

return registration;

}


@Bean

public FilterRegistrationBean authFilterRegistration() {

FilterRegistrationBean registration = new FilterRegistrationBean(new AuthFilter());

registration.addUrlPatterns("/webapi/*"); //

registration.addInitParameter("paramName", "paramValue"); //

registration.setName("authFilter");

registration.setOrder(2);

return registration;

}

 

注意:

1、如果指定了 Order 属性,执行的顺序与注册的顺序是无关的;

2、数字越小,优先级越高;

关于 @Order 注解

有文章提到使用 @Order 注解来指定顺序,亲测无效。