Spring boot 配置Filter過濾器
阿新 • • 發佈:2018-12-10
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 註解來指定順序,親測無效。