How to apply spring boot filter based on URL pattern?

前端 未结 3 880
渐次进展
渐次进展 2020-12-14 17:24

I have created a spring boot filter - implements GenericFilterBean with @Component annotation.

@Component 
public class MyAuthentic         


        
3条回答
  •  眼角桃花
    2020-12-14 17:58

    @user1283002 I think it's possible to do using @WebFilter. I just stumbled upon this article. As per the article (haven't tried myself):

    @WebFilter(urlPatterns = "/api/count")
    public class ExampleFilter implements Filter{
        // ..........
    }
    
    // and let Spring know to scan to find such @WebFilter annotation in your config
    // class by using the @ServletComponentScan annotation like
    
    @ServletComponentScan
    @SpringBootApplication
    public class MyApplication extends SpringBootServletInitializer {
    
        public static void main(String[] args) throws Exception {
            SpringApplication.run(MyApplication.class, args);
        }
    
       // ..........
    
    }
    

    EDIT: After further reading the docs for the @ServletComponentScan I came across an interesting disclaimer

    Scanning is only performed when using an embedded webserver

    Which means that when deploying our application in a web container (eg: Apache Tomcat) this class won't get scanned by the Spring framework and therefore any spring config on it (if any) won't be applied.

    If there is no Spring config to be made you are good to go without any further changes, if not just add the @Component scan to the filter and make sure it's package is in the path of your @ComponentScan annotation.

提交回复
热议问题