initParams 在 WebFilter 注释中不起作用

0 web spring-boot

我在 spring-boot 创建的 java web 项目中使用以下注释创建了一个过滤器:

@Order(2)
@Component
@WebFilter(
        filterName = "jwtFitler", 
        urlPatterns = "/*", 
        initParams = { @WebInitParam(name = "excludedPaths", value = "login, hello") }
)
Run Code Online (Sandbox Code Playgroud)

但是,initParams 不起作用,excludedPaths 和excludedUrls 始终为空。谁能帮我说说为什么?

public class MyFilter implements Filter {

    private String[] excludedUrls;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

        String excludedPaths = filterConfig.getInitParameter("excludedPaths");
        System.out.println("excludedPaths:" + excludedPaths);

        if(!StringUtils.isEmpty(excludedPaths))
            excludedUrls = excludedPaths.split(",");

        System.out.println("excludedUrls:" + excludedUrls);
    }

    //......
}
Run Code Online (Sandbox Code Playgroud)

And*_*son 7

由于您使用了@Component,您的过滤器被发现是一个普通的 Spring 组件。因此,@WebFilter配置无效。

如果您希望 Spring Boot 扫描 Servlet 组件(@WebFilter,@WebListener@WebServlet),您需要使用@ServletComponentScan. 通常,该注解会与@SpringBootApplication. 有了它,您应该@Component从过滤器中删除。