【发布时间】:2013-08-06 22:58:27
【问题描述】:
我想注册一个自定义的HandlerMethodArgumentResolver 可以处理以下@Controller 处理程序方法定义
@RequestMapping(method = RequestMethod.POST)
public String createDomain(@Valid Domain domain, BindingResult errors, @RequestParam("countryId") Long countryId) {
我可以注册我的解析器,它只是通过请求参数创建一个Domain 对象,方法是从WebMvcConfigurerAdapter 覆盖addArgumentResolver()。当 Spring 尝试解析 Domain 参数时,它会遍历其 HandlerMethodArgumentResolver 列表(有很多)并选择supports() 它的第一个。
在上面的示例中,虽然我的解析器将被调用并且我的 Domain 参数将被初始化,但 @Valid 注释不会被处理并且BindingResult的解析器, ErrorsMethodArgumentResolver 将失败,因为它需要处理程序方法中的 @ModelAttribute、@RequestBody 或 @RequestPart 参数,而我没有。
如果我尝试通过添加 @ModelAttribute 来修复它
@RequestMapping(method = RequestMethod.POST)
public String createDomain(@Valid @ModelAttribute Domain domain, BindingResult errors, @RequestParam("countryId") Long countryId) {
HandlerMethodArgumentResolver 实现 ModelAttributeMethodProcessor 将首先使用 supports() 检查并在我的自定义解析器之前解析参数(使用 @ModelAttribute 和 @Valid)。 BindingResult 不会失败,但我不会在 Domain 实例上拥有我的自定义创建行为。
我可以复制粘贴验证代码并添加到ModelAttributeMethodProcessor 中的模型,但我希望有一种更简单的方法来解析我的参数并执行验证,而无需向模型添加对象。有没有这样的方法?
【问题讨论】: