一、
1、作用
加@Order()注解,在注解中加入数字,数字越小,优先级越高,最先执行。
2、使用方法
(1)自定义顺序
@Component
@Order(1)
public class XxxFilter extends OncePerRequestFilter{}
@Component
@Order(2)
public class Xxx1Filter extends OncePerRequestFilter{}
(2)使用枚举
1)HIGHEST_PRECEDENCE
代表这个过滤器在众多过滤器中级别最高,也就是过滤的时候最先执行,这时执行的顺序为:
2)LOWEST_PRECEDENCE
表示级别最低,最后执行过滤操作
3、和配置文件的优先级问题
filter的执行顺序除了可以用上面的@Order注解外,还可以通过配置文件设置,这时配置文件设置的优先级--》注解设置的优先级。如我两个filter都设置为Ordered.HIGHEST_PRECEDENCE + 1,其中一个在配置文件设置的,另外一个通过注解设置的,这时配置文件设置的那个会先执行。
package com.demo.security.config;
import com.demo.security.filter.UrlTwoFilter;
import com.demo.security.interceptor.ParamInterceptor;
import com.demo.security.interceptor.ParamOneInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.List;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Autowired
private ParamInterceptor paramInterceptor;
@Autowired
private ParamOneInterceptor paramOneInterceptor;
@Autowired
private UrlTwoFilter twoFilter;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(paramOneInterceptor);
registry.addInterceptor(paramInterceptor).addPathPatterns("/**");
//registry.addInterceptor(paramOneInterceptor);
}
@Bean
public FilterRegistrationBean<UrlTwoFilter> getIpFilter() {
FilterRegistrationBean<UrlTwoFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(twoFilter);
registrationBean.setEnabled(true);
registrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE + 1);
registrationBean.setUrlPatterns(List.of("/*"));
return registrationBean;
}
}
@Component
@Slf4j
//@Order(1)
@Order(Ordered.HIGHEST_PRECEDENCE+1)
public class UrlOneFilter extends OncePerRequestFilter