企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
###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`: ```java @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。例如: ```java @Bean public FilterRegistrationBean registration(MyFilter filter) { FilterRegistrationBean registration = new FilterRegistrationBean(filter); registration.setEnabled(false); return registration; } ```