栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何:spring摆脱@Validate进行自动控制器验证?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何:spring摆脱@Validate进行自动控制器验证?

我终于找到了一个可行的解决方案,从Spring配置的角度来看,这可能不是最佳选择(正如我所说的,我是Spring初学者)。

想法是修改参数解析器(实现

HandlerMethodArgumentResolver
的参数解析器),用
@RequestBody
注释替换与参数关联的参数解析器。创建从默认一个(这是一个继承的类
RequestResponseBodyMethodProcessor
),并覆盖在类层次结构,其efectively确定是否执行验证或不的方法(基于在存在
@Valid
@Validated
@ValidXxxxxx
注释作为默认行为),使得始终验证无进一步检查。

所以这是代码(我正在使用Java 8 BTW):

扩展

RequestResponseBodyMethodProcessor
定义验证策略(在这种情况下,始终验证):

public class MyRequestResponseBodyMethodProcessor extends RequestResponseBodyMethodProcessor {    public MyRequestResponseBodyMethodProcessor(List<HttpMessageConverter<?>> converters) {        super(converters);    }    @Override    protected void validateIfApplicable(WebDataBinder binder, MethodParameter parameter) {        binder.validate();      // always validating @RequestMapping annotated parameters ;)    }}

定义一个

@Configuration
替换默认参数解析器的类:

@Configurationpublic class MyValidationAdapterConfigurer {    @Autowired    private RequestMappingHandlerAdapter requestMappingHandlerAdapter;    // Injecting your own resolver    @Autowired    private RequestResponseBodyMethodProcessor requestResponseBodyMethodProcessor;    @PostConstruct    public void init() {        // Don't know why but, removing the target resolver and adding the injected one to the end does not work!        // Must be something related with the resolvers ordering. So just replacing the target in the same position.        final List<HandlerMethodArgumentResolver> mangledResolvers = requestMappingHandlerAdapter.getArgumentResolvers().stream() .map(resolver -> resolver.getClass().equals(RequestResponseBodyMethodProcessor.class) ?     requestResponseBodyMethodProcessor: resolver) .collect(Collectors.toList());        requestMappingHandlerAdapter.setArgumentResolvers(mangledResolvers);    }}

最后,配置Spring以在您的Application配置类中交付您的自定义Bean:

@Configuration@PropertySource("classpath:api.properties")public class MyRestApiConfiguration {    @Bean    @Autowired    RequestResponseBodyMethodProcessor requestResponseBodyMethodProcessor(List<HttpMessageConverter<?>> converters) {        return new MyRequestResponseBodyMethodProcessor(converters);    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/568717.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号