手动调用Spring Annotation Validation [英] Manually call Spring Annotation Validation
问题描述
我使用Hibernate和Spring Annotations进行了很多验证,如下所示:
public class Account {
@NotEmpty(groups = {Step1.class,Step2.class})
私人字符串名称;
@NotNull(groups = {Step2.class})
private long accountNumber;
public interface Step1 {}
public interface Step2 {}
}
然后在控制器中调用参数:
public String saveAccount(@ModelAttribute @Validated( {Account.Step1.class})帐户帐户,BindingResult结果){
//一些更多的代码和东西在这里
return;
}
但是我想根据控制器中的某些逻辑来决定使用的组方法。有没有办法手动调用验证?类似于 result = account.validate(Account.Step1.class)
?
我知道创建自己的Validator类,但这是我想避免的,我宁愿只在类变量本身使用注释。
在他的回答中比 Jaiwo99 更进一步: // org.springframework.validation.SmartValidator - 由
// LocalValidatorFactoryBean实现,这很有趣,因为它本身不是FactoryBean(只是说)
@Autowired
SmartValidator验证器;
public String saveAccount(@ModelAttribute账户,BindingResult结果){
// ...定制逻辑
validator.validate(account,result,Account.Step1.class) ;
if(result.hasErrors()){
// ...绑定或验证错误
} else {
// ...无错误
}
return;
}
而 SmartValidator JavaDoc的强制性链接,如果您有兴趣的话。
I'm doing a lot of our validation with Hibernate and Spring Annotations like so:
public class Account {
@NotEmpty(groups = {Step1.class, Step2.class})
private String name;
@NotNull(groups = {Step2.class})
private Long accountNumber;
public interface Step1{}
public interface Step2{}
}
And then in the controller it's called in the arguments:
public String saveAccount(@ModelAttribute @Validated({Account.Step1.class}) Account account, BindingResult result) {
//some more code and stuff here
return "";
}
But I would like to decide the group used based on some logic in the controller method. Is there a way to call validation manually? Something like result = account.validate(Account.Step1.class)
?
I am aware of creating your own Validator class, but that's something I want to avoid, I would prefer to just use the annotations on the class variables themselves.
Going a step further than Jaiwo99 in his answer:
// org.springframework.validation.SmartValidator - implemented by
// LocalValidatorFactoryBean, which is funny as it is not a FactoryBean per se (just saying)
@Autowired
SmartValidator validator;
public String saveAccount(@ModelAttribute Account account, BindingResult result) {
// ... custom logic
validator.validate(account, result, Account.Step1.class);
if (result.hasErrors()) {
// ... on binding or validation errors
} else {
// ... on no errors
}
return "";
}
And the mandatory link to SmartValidator JavaDoc if you are interested.
这篇关于手动调用Spring Annotation Validation的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!