spring boot 自定义HandlerMethodArgumentResolver做请求参数校验时,如果controller中Action方法参数实体添加了@RequestBody注解会引起自定义的HandlerMethodArgumentResolver 无法执行,此时只要将@RequestBody注解删除即可。具体原因还要查资料!
-------------------------------------------------------
上面问题原因是:spring 会加载多个 HandlerMethodArgumentResolver ,自定义的会加载在最后,添加了@RequestBody注解的参数在之前的HandlerMethodArgumentResolver 处理完毕后自定义的就不会处理了,所以导致自定义的HandlerMethodArgumentResolver 无法执行
-------------------------------------------------------
上面方法还是有问题:把@RequestBody注解去掉后使用swagger api页面会无法加载POST请求body参数字段,解决方法是使用@RequestBody注解,同时调整HandlerMethodArgumentResolver的顺序,将自定义的HandlerMethodArgumentResolver前置,在
WebConfig 中使用如下代码:
@Configuration public class WebConfig extends WebMvcConfigurationSupport { @Autowired RequestMappingHandlerAdapter adapter; /** * 设置自定义 MethodArgumentResolver 优先级 */ @PostConstruct public void post() { List<HandlerMethodArgumentResolver> argumentResolvers = new ArrayList<>(adapter.getArgumentResolvers()); List<HandlerMethodArgumentResolver> customResolvers = adapter.getCustomArgumentResolvers(); if (customResolvers != null) { argumentResolvers.removeAll(customResolvers); argumentResolvers.addAll(0, customResolvers); } // 自定义的Base64RequestMethodArgumentsResolver前置 argumentResolvers.add(0, new Base64RequestMethodArgumentsResolver()); adapter.setArgumentResolvers(argumentResolvers); } /** * searchable参数解析器 */ @Override protected void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) { // argumentResolvers.add(new Base64RequestMethodArgumentsResolver()); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("swagger-ui.html") .addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/"); } }