1. 程式人生 > >spring boot三大器之Filter過濾器實現

spring boot三大器之Filter過濾器實現

1、通過 @WebFilter 註解來配置

@Component
@WebFilter(urlPatterns = "/webapi/*", filterName = "authFilter")
public class AuthFilter implements Filter {
    ......
}

2、通過 @Bean 註解來配置 我這個是寫在帶 @SpringBootApplication 註解的類裡面的。

@Slf4j
@SpringBootApplication
public class Application extends SpringBootServletInitializer {

	@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、數字越小,優先順序越高;