Spring 拦截器在 Spring 数据 REST URL 中不起作用

Spring Interceptor not working in Spring Data REST URLs

我正在使用 Spring Data Rest 和 JPA 开发一个项目,我正在尝试配置一个 HTTP 拦截器。根据参考文档, 在 Spring Web MVC Docs - Handler Mapping Interceptor 中可用,我创建了一个扩展 HandlerInterceptorAdapter 的组件,如下所示:

@Component
public class DBEditorTenantInterceptor extends HandlerInterceptorAdapter {

    Logger logger = LoggerFactory.getLogger(DBEditorTenantInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
         logger.debug("********** INTERCEPTION SUCCESSFUL **********");
         return true;
    }
}

然后,通过扩展 WebMvcConfig 注册拦截器(如 Spring Web MVC Docs - Config Interceptors

中所述
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Autowired
    DBEditorTenantInterceptor dbEditorTenantInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
         registry.addInterceptor(dbEditorTenantInterceptor)
         .addPathPatterns("/**");
    }

}

当我向 Spring 数据 REST(例如 /helloworld)未使用的任何 URL 发出 HTTP 请求时,拦截器按预期工作,正如我看到的记录器输出

017-10-26 13:16:24.689 DEBUG 17012 --- [p-nio-80-exec-4] c.c.v.d.DBEditorTenantInterceptor        : ********** INTERCEPTION SUCCESSFUL **********

但是,当 URL 被 spring 数据 rest 使用时,我的拦截器不会被调用。这适用于所有 URLs,例如 /api/{existing entity in model}

为什么我的拦截器没有为 Spring Data Rest URLs 调用?我该怎么做才能让我的拦截器对所有请求都起作用?

非常感谢。

通过声明一个 MappedInterceptor 类型的 bean 并用我的拦截器注入它 - 它扩展了 HandlerInterceptorAdapter,我的拦截器被 Spring Data Rest 选中,现在适用于应用程序上的任何 URL。

这转化为以下实现(替换我原来问题中的那个):

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Autowired
    DBEditorTenantInterceptor dbEditorTenantInterceptor;

    @Bean
    public MappedInterceptor dbEditorTenantInterceptor() {
        return new MappedInterceptor(new String[]{"/**"}, dbEditorTenantInterceptor);
    }

}

不幸的是,我在 Spring 文档中找不到对此的任何引用。

我只想在@AndrewP 的 ...

中添加一些内容

如果您在项目中使用仅Spring REST 数据,并且您想要拦截您的Spring 存储库和@RepositoryRestController s,你只需要定义一个@Bean方法,语法如下:

@Bean
public MappedInterceptor someMethodName() {
    return new MappedInterceptor(
        null,  // => maps to any repository
        new YourInterceptorImpl()
    );
}

此类方法必须在任何 @Configuration 注释中声明 class;这样 class 不需要 implement/extend 任何特殊的东西(例如,WebMvcConfigurerAdapter)......网络上的许多文档都暗示了这一点,但是我认为它仅适用于处理 Spring MVC 资源!!!

拦截器实现必须实现 HandlerInterceptor 或扩展 HandlerInterceptorAdapter...