Spring Boot Filter 注入方式

November 22, 2022 作者: yijianhao 分类: SpringBootjava 浏览: 366 评论: 0

javax.servlet.Filter是处于Servlet级别的过滤器,不属于spring。一个请求会先经过web服务器(Tomcat、Jetty…)然后就是Filter了。以下是Filter的官方文档,以及个人的翻译:

A filter is an object that performs filtering tasks on either the request to a resource (a servlet or static content), or on the response from a resource, or both.
filter(过滤器)是对资源请求(servlet 或静态内容)以及资源响应执行过滤任务的对象(译者:对requests和response进行过滤的对象)
Filters perform filtering in the doFilter method. Every Filter has access to a FilterConfig object from which it can obtain its initialization parameters, and a reference to the ServletContext which it can use, for example, to load resources needed for filtering tasks.
过滤器在doFiler方法中执行过滤,每个过滤器都可以访问一个FilterConfig对象,从中获取初始化参数,以及对他可以使用的ServletContext进行引用,例如,为过滤任务加载所需资源。
Filters are configured in the deployment descriptor of a web application.
过滤器在web应用程序的部署描述符中配置。
Examples that have been identified for this design are:
已有使用Filter的设计方案示例:

  • Authentication Filters
  • Logging and Auditing Filters
  • Image conversion Filters
  • Data compression Filters
  • Encryption Filters
  • Tokenizing Filters
  • Filters that trigger resource access events
  • XSL/T filters
  • Mime-type chain Filter
    自: Servlet 2.3

在spring boot中可以使用以下两种方式进行注入:

1. 使用@WebFiler注解

@WebFilter(urlPatterns = "/*", filterName = "jettyFilter")
public class CustomerFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        ... ...
        chain.doFilter(request, response);
    }

}

主函数中需要加上@ServletComponentScan注解,这个注解与@ComponentScan类似,有一个默认的包扫描方式,也可以定义需要扫描的包

2. 通过Bean注入

    @Bean(name = "customer-filter")
    public FilterRegistrationBean<MyFilter> filter() {
        final FilterRegistrationBean<MyFilter> dynamic = new FilterRegistrationBean<>();
        dynamic.setOrder(Ordered.HIGHEST_PRECEDENCE);
        dynamic.setFilter(new MyFilter());
        dynamic.setUrlPatterns(Collections.singleton("/*"));
        return dynamic;
    }

通过FilterRegistrationBean类可以方便的注入Filter,这里有时间再补充,有需要的话,可以访问这个链接去了解更多:https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/web/servlet/FilterRegistrationBean.html


评论