手动调用 Spring Annotation Validation [英] Manually call Spring Annotation Validation
问题描述
我正在使用 Hibernate 和 Spring Annotations 进行大量验证,如下所示:
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 "";
}
但我想根据控制器方法中的某些逻辑来决定使用的组.有没有办法手动调用验证?类似于 result = account.validate(Account.Step1.class)
?
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)
?
我知道创建您自己的 Validator 类,但这是我想避免的,我更愿意只使用类变量本身的注释.
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.
推荐答案
Spring 提供 LocalValidatorFactoryBean,它实现了 Spring SmartValidator
接口以及 Java Bean 验证 Validator
接口.
Spring provides LocalValidatorFactoryBean, which implements the Spring SmartValidator
interface as well as the Java Bean Validation Validator
interface.
// org.springframework.validation.SmartValidator - implemented by LocalValidatorFactoryBean
@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 "";
}
这篇关于手动调用 Spring Annotation Validation的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!