首页 文章

如何在Spring数据休息中添加自定义拦截器(spring-data-rest-webmvc 2.3.0)

提问于
浏览
5

我正在研究spring数据休息服务并面临自定义拦截器中的一些问题 . 之前我使用了spring-data-rest-webmvc 2.2.0并以下列方式添加了拦截器 .

public RequestMappingHandlerMapping repositoryExporterHandlerMapping() {
        RequestMappingHandlerMapping mapping = super
                .repositoryExporterHandlerMapping();

        mapping.setInterceptors(new Object[] { new MyInterceptor() });

        return mapping;
}

它对我来说非常好 . 但是当我升级到spring-data-rest-webmvc 2.3.0版本时,我注意到handlerMapping隐藏在DelegatingHandlerMapping后面 . 因此我尝试以下列方式添加拦截器 .

在我的一个配置类中,我扩展了RepositoryRestMvcConfiguration类并覆盖了它的方法 .

public class AppConfig extends RepositoryRestMvcConfiguration {
@Autowired ApplicationContext applicationContext;

@Override
public DelegatingHandlerMapping restHandlerMapping()
    {
        RepositoryRestHandlerMapping repositoryMapping = new RepositoryRestHandlerMapping(super.resourceMappings(), super.config());
        repositoryMapping.setInterceptors(new Object[] { new MyInterceptor()});
        repositoryMapping.setJpaHelper(super.jpaHelper());
        repositoryMapping.setApplicationContext(applicationContext);
        repositoryMapping.afterPropertiesSet();

        BasePathAwareHandlerMapping basePathMapping = new BasePathAwareHandlerMapping(super.config());
        basePathMapping.setApplicationContext(applicationContext);
        basePathMapping.afterPropertiesSet();
        List<HandlerMapping> mappings = new ArrayList<HandlerMapping>();
        mappings.add(basePathMapping);
        mappings.add(repositoryMapping);

        return new DelegatingHandlerMapping(mappings);

    }
}

但在添加之后,我的一些存储库操作(存储库上的findAll()操作)开始失败 . 如果我删除了这个拦截器,那些操作工作正常 . (在这个拦截器中我只是验证用户 . )因此我无法理解这里的问题 . 我是以错误的方式添加拦截器吗?有没有其他方法来添加拦截器?

1 回答

  • 11

    你不应该使用 repositoryMapping.setInterceptors() - 它会使Spring放置在那里的内部拦截器,这可能是某些方法停止工作的原因 .

    我建议你覆盖 jpaHelper() 方法并将你的拦截器放入 RepositoryRestMvcConfiguration 中的 JpaHelper 对象中 . Spring会将它们应用到全局拦截器列表中 .

    但是,如果您只需要身份验证,为什么不使用Spring Security过滤器?

    编辑:上述解决方案仅适用于 RepositoryRestHandlerMapping ,不适用于 BasePathAwareHandlerMapping .

    我建议你在某处声明一个自定义 MappedInterceptor bean:

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

    根据我对源代码的理解,Spring应该自动将这个拦截器添加到所有请求处理程序中 .

相关问题