我知道@Valid在这样的示例中,注释会指示spring验证例如根据JSR-303的Controller参数:
@Valid
@GetMapping("/test") public TestDTO testDTO(@Valid TestDTO testDTO){ return testDTO; }
但是我希望能够以某种方式配置Spring以在所有控制器中启用验证,而无需明确指定@Valid注释。
有可能吗?一些Spring配置?利用AOP吗?…
我终于找到了一个可行的解决方案,从Spring配置的角度来看,这可能不是最佳选择(正如我所说的,我是Spring初学者)。
想法是修改参数解析器(实现HandlerMethodArgumentResolver的参数解析器),用@RequestBody注释替换与参数关联的参数解析器。创建从默认一个(这是一个继承的类RequestResponseBodyMethodProcessor),并覆盖在类层次结构,其efectively确定是否执行验证或不的方法(基于在存在@Valid,@Validated,@ValidXxxxxx注释作为默认行为),使得始终验证无进一步检查。
HandlerMethodArgumentResolver
@RequestBody
RequestResponseBodyMethodProcessor
@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替换默认参数解析器的类:
@Configuration
@Configuration public 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); } }