听起来您想要一个实现org.springframework.validation.Validator
.
@Component
public class MyValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return MyBean.class.isAssignableFrom(clazz);
}
@Override
public void validate(Object target, Errors errors) {
MyBean myBean = (MyBean) target;
if (StringUtils.isBlank(myBean.getProperty("state"))) {
errors.rejectValue("state", "blank");
}
}
}
在您的控制器中,您将执行如下手动验证:
@Autowired
private MyValidator myValidator;
@RequestMapping(value = "save", method = RequestMethod.POST)
public String save(@ModelAttribute("myBean") MyBean myBean, BindingResult result) {
myValidator.validate(myBean, result);
if (result.hasErrors()) {
...
}
...
}