spring常用注解(10)@Order

一、

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
相关推荐
newerp3 分钟前
Golang 调度循环:Go runtime 如何永不停歇地找人干活
后端·程序员·go
用户27462129172808 分钟前
深入 Spring AI ChatClient:从一行代码到 LLM 调用的完整旅程
spring
明月_清风21 分钟前
AI 时代,为什么架构师又开始谈"本体论"?
人工智能·后端·agent
用户094248568031 小时前
第3章:OpenJDK从源码到字节码——Class 文件与 javac 管线
java·jvm
azhou的代码园1 小时前
基于RFM模型的中小型企业客户管理系统
java·人工智能·spring boot·毕业设计
君顾11 小时前
酒吧点餐小程序系统开发实战:从架构设计到上线全流程指南
java·开发语言·酒吧
行百里er1 小时前
BeanPostProcessor:包装 Feign Client
spring boot·后端·监控
子非鱼a1 小时前
【WEB】[SWPU2019]Web1
java·服务器·前端
花生了什么事o2 小时前
自定义Spring Boot Starter全流程
java·spring boot·后端