如何让多个 Spring HandlerInterceptor 以特定的顺序执行

How to make multiple Spring HandlerInterceptors execute in a specific order

我目前正在处理 Spring 启动项目。我依赖于具有拦截器(LibraryProjectInterceptor.java)和 public class LibraryProjectConfig implements WebMvcConfigurer 的库项目,并覆盖 addInterceptors() 方法以添加 LibraryProjectInterceptorInterceptorRegistry。在我添加这个库项目依赖的实际项目中,我创建了一个拦截器(ActualProjectInterceptor),需要在 LibraryProjectInterceptor 执行后执行。我尝试将 @Order(value = Ordered.LOWEST_PRECEDENCE) 添加到 ActualProjectInterceptor 以使其在 LibraryProjectInterceptor 之后执行,但它不起作用。谁能帮帮我

图书馆项目:

public class LibraryProjectInterceptor implements HandlerInterceptor {
 ......
}




  @Configuration
  @EnableWebMVC
  public class LibraryProjectConfig implements WebMvcConfigurer {
    ......
        @Override
            public void addInterceptors(InterceptorRegistry registry) {
                registry.addInterceptor(LibraryProjectInterceptor);
            }
    ......
    }

实际项目: pom.xml

 ......

<dependencies>
 <dependency> 
   <groupId>com.example</groupId>
   <artifactId>library-project</artifactId>
   <version>1.0.16</version>
 </dependency>
 ......

@Component
@Order(value = Ordered.LOWEST_PRECEDENCE)
public class ActualProjectInterceptor implements HandlerInterceptor{
.......
}

@SpringBootApplication
public class ActualProjectConfig implements WebMvcConfigurer {
......
    @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(ActualProjectInterceptor);
        }
......
}

试试这个,我希望它会起作用。

@Component
public class ActualProjectInterceptor implements HandlerInterceptor {}

@SpringBootApplication
public class ActualProjectConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(ActualProjectInterceptor)
                .order(Ordered.LOWEST_PRECEDENCE);
    }
}

addInterceptor() 方法创建 InterceptorRegistration DSL 对象,该对象具有 order() 方法来指定您需要的内容。