两种方式
第一种通过FilterRegistrationBean
@Bean
public FilterRegistrationBean filterRegistrationBean(){
return new FilterRegistrationBean(errorPageFilter());
}
@Bean
public Filter errorPageFilter(){
ErrorPageFilter errorPageFilter = new ErrorPageFilter();
ErrorPage notFind = new ErrorPage("/404");
errorPageFilter.addErrorPages(notFind);
return errorPageFilter;
}
第二种通过DelegatingFilterProxyRegistrationBean
@Bean
public DelegatingFilterProxyRegistrationBean delegatingFilterProxyRegistrationBean(){
return new DelegatingFilterProxyRegistrationBean("errorPageFilter");
}
@Bean("errorPageFilter")
public Filter errorPageFilter(){
ErrorPageFilter errorPageFilter = new ErrorPageFilter();
ErrorPage notFind = new ErrorPage("/404");
errorPageFilter.addErrorPages(notFind);
return errorPageFilter;
}
二者都是继承同一个父类AbstractFilterRegistrationBean,只是DelegatingFilterProxyRegistrationBean还实现了ApplicationContextAware,注入了ApplicationContext实例,用于查找指定的Filter实例,最终构建的是一个代理Filter实例(DelegatingFilterProxy);FilterRegistrationBean中维护的是目标Filter,结果都是将Filter注册到ServletContext中,推荐使用FilterRegistrationBean。