我有一个简单的 Foo 类,像这样说:
public class Foo {
@NotNull
private String bar;
public String getBar(){ return bar; }
public void setBar(String _bar){ this.bar = _bar; }
}
现在,我有一个 Controller REST 方法,它采用一个 Foos 数组(或集合),我想确保每个 Foo 都有一个非空的 bar 属性。 我认为使用 @Valid 注释可以解决问题,但似乎并非如此:
@Controller
public class MyController {
@RequestMapping(value="/foos", method=RequestMethod.POST)
public @ResponseBody String createFoos(@Valid @RequestBody Foo[] foos){
// blah blah blah
return "yeah";
}
}
注意:它也不适用于 List
当我们有“多个”对象(在集合或数组中)时,Spring 验证似乎不起作用。
我什至尝试使用自定义注释实现 HandlerMethodArgumentResolver,但我不知道如何在 BindingResult 中定义“索引属性名称”。
如果有人知道这个问题的解决方法,将不胜感激! :)
最佳答案
我认为您在实现过程中遗漏了几件事。您需要使用对象图的概念来完成这项工作。
您的 Foo 类在其字段之一上进行了@NotNull 验证,但是您还没有真正表达需要对集合有效的内容。
来自 Hibernate 引用:
Object graph validation also works for collection-typed fields. That means any attributes that are arrays, implement java.lang.Iterable (especially Collection, List and Set) or implement java.util.Map can be annotated with @Valid, which will cause each contained element to be validated, when the parent object is validated.
所以你的代码会变成
@Controller
public class MyController {
@RequestMapping(value="/foos", method=RequestMethod.POST)
public @ResponseBody String createFoos(@Valid @NotNull @RequestBody Foo[] foos){
// blah blah blah
return "yeah";
}
}
关于java - Spring 3,JSR-303(bean 验证)和验证集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8828457/