gpt4 book ai didi

spring-data-rest - 如何在Spring Data Rest中添加自定义拦截器(spring-data-rest-webmvc 2.3.0)

转载 作者:行者123 更新时间:2023-12-04 13:38:12 28 4
gpt4 key购买 nike

我正在研究Spring Data Rest Services,并在自定义拦截器中遇到一些问题。之前我使用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()操作)开始失败。如果我删除了此拦截器,则这些操作将正常进行。 (在此拦截器中,我只是对用户进行身份验证。)
因此,我在这里无法理解问题。我是否以错误的方式添加了拦截器?还有其他方法可以添加拦截器吗?

最佳答案

您不应该使用repositoryMapping.setInterceptors()-它会破坏Spring放置在其中的内部拦截器,这可能就是某些方法停止工作的原因。

我建议您重写jpaHelper()方法,并将拦截器放入JpaHelper中的RepositoryRestMvcConfiguration对象中。 Spring将它们添加到全局拦截器列表中。

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

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

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

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

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

关于spring-data-rest - 如何在Spring Data Rest中添加自定义拦截器(spring-data-rest-webmvc 2.3.0),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32916260/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com