手动调用Spring注释验证

我正在使用Hibernate和Spring Annotations进行很多验证,如下所示:

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{}

}

然后在控制器中,在参数中调用它:

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)什么?

我知道要创建自己的Validator类,但这是我要避免的事情,我宁愿只在类变量本身上使用批注。

回答:

比Jaiwo99更进一步:

// 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 "";

}

以上是 手动调用Spring注释验证 的全部内容, 来源链接: utcz.com/qa/423029.html

回到顶部