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
相关推荐
一只会写代码的猫1 天前
面向高性能计算与网络服务的C++微内核架构设计与多线程优化实践探索与经验分享
java·开发语言·jvm
萤丰信息1 天前
智慧园区能源革命:从“耗电黑洞”到零碳样本的蜕变
java·大数据·人工智能·科技·安全·能源·智慧园区
曹牧1 天前
Eclipse为方法添加注释
java·ide·eclipse
我叫张小白。1 天前
Spring Boot拦截器详解:实现统一的JWT认证
java·spring boot·web·jwt·拦截器·interceptor
uzong1 天前
Mermaid: AI 时代画图的魔法工具
后端·架构
Gerardisite1 天前
如何在微信个人号开发中有效管理API接口?
java·开发语言·python·微信·php
q***69771 天前
Spring Boot与MyBatis
spring boot·后端·mybatis
闲人编程1 天前
Python的导入系统:模块查找、加载和缓存机制
java·python·缓存·加载器·codecapsule·查找器
故渊ZY1 天前
Java 代理模式:从原理到实战的全方位解析
java·开发语言·架构
匿者 衍1 天前
POI读取 excel 嵌入式图片(支持wps 和 office)
java·excel