70.1.1 使用Spring bean添加Servlet, Filter或Listener

想要添加ServletFilter或Servlet*Listener,你只需要为它提供一个@Bean定义,这种方式很适合注入配置或依赖。不过,需要注意的是它们不会导致其他很多beans的热初始化,因为它们需要在应用生命周期的早期进行安装(让它依赖DataSource或JPA配置不是好主意),你可以通过懒加载突破该限制(在第一次使用时才初始化)。

对于FiltersServlets,你可以通过FilterRegistrationBeanServletRegistrationBean添加映射和初始化参数。

在一个filter注册时,如果没指定dispatcherType,它将匹配FORWARDINCLUDEREQUEST。如果启用异步,它也将匹配ASYNC。如果迁移web.xml中没有dispatcher元素的filter,你需要自己指定一个dispatcherType

  1. @Bean
  2. public FilterRegistrationBean myFilterRegistration() {
  3. FilterRegistrationBean registration = new FilterRegistrationBean();
  4. registration.setDispatcherTypes(DispatcherType.REQUEST);
  5. ....
  6. return registration;
  7. }

禁止Servlet或Filter的注册

如上所述,任何ServletFilter beans都将自动注册到servlet容器。不过,为特定的FilterServlet bean创建一个registration,并将它标记为disabled,可以禁用该filter或servlet。例如:

  1. @Bean
  2. public FilterRegistrationBean registration(MyFilter filter) {
  3. FilterRegistrationBean registration = new FilterRegistrationBean(filter);
  4. registration.setEnabled(false);
  5. return registration;
  6. }