的實體:
package org.ibp.soq;
public class MyEntity {
private String field1;
private String field2;
//..getters and setters
}
驗證的實體:
package org.ibp.soq;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
@Component
public class MyEntityValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return MyEntity.class.equals(clazz);
}
@Override
public void validate(Object target, Errors errors) {
MyEntity myEntity = (MyEntity) target;
// Logic to validate my entity
System.out.print(myEntity);
}
}
和
其餘控制器批量put方法:
package org.ibp.soq;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/myEntity")
public class MyEntityRestResource {
@Autowired
private MyEntityValidator myEntityValidator;
@InitBinder
protected void initBinder(final WebDataBinder binder) {
binder.addValidators(this.myEntityValidator);
}
@RequestMapping(method = RequestMethod.PUT)
public void bulkCreate(@RequestBody @Valid List<MyEntity> myEntities) {
// Logic to bulk create entities here.
System.out.print(myEntities);
}
}
當我做一個PUT請求,該資源與下列的請求正文:
[
{
"field1": "AA",
"field2": "11"
},
{
"field1": "BB",
"field2": "22"
}
]
我得到的錯誤是:
"Invalid target for Validator [[email protected]]: [[email protected], [email protected]]"
我可以理解,這是因爲MyEntityValidator
「支持」單個MyEntity
驗證,不合法爲ArrayList<MyEntity>
。
MyEntityValidator
如果我在請求正文中有單個MyEntity
對象,並且參數@RequestBody @Valid MyEntity myEntity
有對應的控制器方法,則完美工作。
如何驗證器設置我已經使用,擴展爲支持收集MyEntity
的驗證?
謝謝!我一定會嘗試這種方法。 –
使用\ @ControllerAdvice將應用CollectionValidator到所有控制器。如果在非集合對象上有另一個\ @Valid註解,會導致「java.lang.IllegalStateException:Validator的無效目標」exeption。 –
改爲使用\ @InitBinder(「attrName」),或者在特定控制器中執行initBinder。 –