未呼叫Spring Boot Servlet筛选器

jmo0nnb3  于 2022-10-30  发布在  Spring
关注(0)|答案(1)|浏览(178)

你好,我是SpringBoot的新手,我正在努力创建一个过滤器;当项目启动时,甚至当我发送API请求时,我创建的过滤器类都不会被调用(未调用init、doFilter目前我没有使用Sping Boot Web,我正在使用Gradle构建Spring Boot,并运行React前端和Spring Boot作为后端。我创建了一个Filter类,它从import javax.servlet.*实现Filter,并使用@Components。如下图所示。

@Component
public class DeviceFilter implements Filter{
    @Autowired
    DeviceRepository deviceRepository;
    private static final Logger LOG = LoggerFactory.getLogger(DeviceFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("INIT FILTER.....");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("DO FILTER.....");
        LOG.info("Logging");
        System.out.println("INFO");
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        System.out.println("DESTORY FILTER.....");
    }
}

此外,我认为我应该在web.xml中添加/ map filter,但由于我使用gradle构建了项目,该项目没有web.xml,因此我创建了一个@Configuration类,在其中Map了过滤器,如下所示。

@Configuration
public class FilterConfig {
    @Bean
    public FilterRegistrationBean<DeviceFilter> filterRegistrationBean(){
        FilterRegistrationBean<DeviceFilter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(new DeviceFilter());
        registrationBean.addUrlPatterns("/*");
        return registrationBean;
    }
}

我是错过了什么还是我做错了什么?请帮助谢谢!PS:此外,当我从主类运行spring Boot 时,控制台打印如下所示

2021-09-10 11:27:51.725  INFO 66959 --- [main] a.m.s.Project    : Starting Project using Java 16 on Bob-MBP-2 with PID 66959 (/Users/bob/Development/project/build/classes/java/main started by bob in /Users/bob/Development/project)
2021-09-10 11:27:51.727  INFO 66959 --- [main] a.m.s.Project    : The following profiles are active: dev
2021-09-10 11:27:52.422  INFO 66959 --- [main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data R2DBC repositories in DEFAULT mode.
2021-09-10 11:27:52.521  INFO 66959 --- [main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 96 ms. Found 16 R2DBC repository interfaces.
2021-09-10 11:27:54.725  INFO 66959 --- [main] o.s.b.web.embedded.netty.NettyWebServer  : Netty started on port 9020
2021-09-10 11:27:54.736  INFO 66959 --- [main] a.m.s.Project    : Started Project in 3.355 seconds (JVM running for 4.041)
hc8w905p

hc8w905p1#

  • 试试这个,它会成功的,你忘了注入DeviceFilter*
@Configuration
public class FilterConfig {
@Autowired
DeviceFilter deviceFilter
    @Bean
    public FilterRegistrationBean<DeviceFilter> filterRegistrationBean(){
        FilterRegistrationBean<DeviceFilter> registrationBean = new 
           FilterRegistrationBean<>();
        registrationBean.setFilter(deviceFilter);
        registrationBean.addUrlPatterns("/*");
        return registrationBean;
    }
}

相关问题