70.1.1 使用Spring bean添加Servlet, Filter或Listener
想要添加Servlet
,Filter
或Servlet*Listener
,你只需要为它提供一个@Bean
定义,这种方式很适合注入配置或依赖。不过,需要注意的是它们不会导致其他很多beans的热初始化,因为它们需要在应用生命周期的早期进行安装(让它依赖DataSource
或JPA配置不是好主意),你可以通过懒加载突破该限制(在第一次使用时才初始化)。
对于Filters
或Servlets
,你可以通过FilterRegistrationBean
或ServletRegistrationBean
添加映射和初始化参数。
注 在一个filter注册时,如果没指定dispatcherType
,它将匹配FORWARD
,INCLUDE
和REQUEST
。如果启用异步,它也将匹配ASYNC
。如果迁移web.xml
中没有dispatcher
元素的filter,你需要自己指定一个dispatcherType
:
@Bean
public FilterRegistrationBean myFilterRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setDispatcherTypes(DispatcherType.REQUEST);
....
return registration;
}
禁止Servlet或Filter的注册
如上所述,任何Servlet
或Filter
beans都将自动注册到servlet容器。不过,为特定的Filter
或Servlet
bean创建一个registration,并将它标记为disabled,可以禁用该filter或servlet。例如:
@Bean
public FilterRegistrationBean registration(MyFilter filter) {
FilterRegistrationBean registration = new FilterRegistrationBean(filter);
registration.setEnabled(false);
return registration;
}