SpringBoot如何在没有注释的情况下设置过滤器的顺序 [英] SpringBoot how to set order of Filter without annotation

查看:27
本文介绍了SpringBoot如何在没有注释的情况下设置过滤器的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 spring 过滤器链中插入(在第一个位置)一个简单的自定义 Cors 过滤器.

I'm trying to insert (at first position) a simple custom Cors filter inside the spring filter chain.

如果我这样做

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter implements Filter {

完美运行我可以通过在 Spring 的 ServletHandler.java 中放置一个断点来验证它

it works perfectly I can verify it by putting a breakpoint in Spring's ServletHandler.java where there the line

chain=getFilterChain(baseRequest, target, servlet_holder);

我只是想知道我是否希望使用 @Componenent 和 @Order 而是将过滤器 bean 定义为应用程序上下文.如何设置过滤器的顺序?

I was just wondering if I wish not to use @Componenent and @Order and instead defining the Filter bean the Application context. How can I set the order of the filters ?

推荐答案

参见示例:在您的类 ServletInitializer 中:

See example: In your class ServletInitializer:

@Bean
 public FilterRegistrationBean requestLogFilter() {
        final FilterRegistrationBean reg = new FilterRegistrationBean(createRequestLogFilter());
        reg.addUrlPatterns("/*");
        reg.setOrder(1); //defines filter execution order
        return reg;
 }

 @Bean
 public RequestLogFilter createRequestLogFilter(){
        return new RequestLogFilter();
 }

我的过滤器的名称是requestLogFilter"

the name of my filter is "requestLogFilter"

警告:不要在过滤器类中使用@Component 注解.

Warning: Don't use @Component annotation at the class Filter.

这篇关于SpringBoot如何在没有注释的情况下设置过滤器的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆