我正在研究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()操作)开始失败。如果我删除了此拦截器,则这些操作将正常进行。(在此拦截器中,我只是对用户进行身份验证。)因此,在这里我无法理解问题。我是否以错误的方式添加了拦截器?还有其他方法可以添加拦截器吗?
您不应该使用repositoryMapping.setInterceptors()
-它会破坏Spring放置在其中的内部拦截器,这可能就是某些方法停止工作的原因。
建议您重写jpaHelper()
method并将拦截器放入中的JpaHelper
对象RepositoryRestMvcConfiguration
。Spring将它们添加到全局拦截器列表中。
但是,再次,如果您只需要身份验证,为什么不使用Spring Security过滤器呢?
编辑:以上解决方案仅适用于RepositoryRestHandlerMapping
,不适用于BasePathAwareHandlerMapping
。
我建议您在MappedInterceptor
某处声明一个自定义bean:
@Bean
public MappedInterceptor myMappedInterceptor() {
return new MappedInterceptor(new String[]{"/**"}, new MyInterceptor());
}
根据我对源代码的理解,Spring应该自动将此拦截器添加到所有请求处理程序中。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句