Ger*_*sch 5 spring spring-mvc spring-aop spring-validator spring-boot
我知道@Valid注释指示spring在这个例子中根据JSR-303验证例如一个Controller参数:
@GetMapping("/test")
public TestDTO testDTO(@Valid TestDTO testDTO){
return testDTO;
}
Run Code Online (Sandbox Code Playgroud)
但我希望能够以某种方式配置Spring以在所有控制器中启用验证,而无需明确指定@Valid注释.
这有可能吗?一些Spring配置?利用AOP?...
我终于找到了一个可行的解决方案,从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 ;)
}
}
Run Code Online (Sandbox Code Playgroud)
定义一个@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);
}
}
Run Code Online (Sandbox Code Playgroud)
最后,配置Spring以在您的Application配置类中交付您的自定义Bean:
@Configuration
@PropertySource("classpath:api.properties")
public class MyRestApiConfiguration {
@Bean
@Autowired
RequestResponseBodyMethodProcessor requestResponseBodyMethodProcessor(List<HttpMessageConverter<?>> converters) {
return new MyRequestResponseBodyMethodProcessor(converters);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1678 次 |
| 最近记录: |