2013-10-04 47 views
22

我做了很多我們的驗證與Hibernate和Spring註解,像這樣:手動調用春註釋驗證

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類,但這是我想要避免的,我寧願只在類變量本身上使用註釋。

回答

32

在他的回答再進一步比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 ""; 
} 

而且mandatory link to SmartValidator JavaDoc如果你有興趣。

+0

OP指定他不想創建一個Validator類,但是從一個單獨的驗證器調用'validator.validate(account,errors,Account.Step1.class)'方便地將錯誤添加到響應實體(如果BindingResult未在控制器中定義)。 – Milanka

11

這裏是JSR 303 spec

Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); 

Driver driver = new Driver(); 
driver.setAge(16); 
Car porsche = new Car(); 
driver.setCar(porsche); 


Set<ConstraintViolation<Driver>> violations = validator.validate(driver); 

一個代碼示例所以,是的,你可以得到驗證工廠驗證實例並運行自己的驗證,然後檢查是否有違規或沒有。您可以在javadoc for Validator中看到它也會接受一組要驗證的組。

顯然,這直接使用JSR-303的驗證,而不是通過春天驗證去,但我相信春天驗證註解將使用JSR-303,如果它在classpath中發現

+3

的事情是,如果你使用Spring MVC,你可能想'BindingResult' /'Errors'的'ConstraintViolation's代替。所以雖然你的回答是正確的,但它不適合這個問題。 –

6

如果你擁有了一切正確的配置,你可以做這個:

@Autowired 
Validator validator; 

然後你可以用它來驗證你的對象。

1

而且也:

@Autowired 
@Qualifier("mvcValidator") 
Validator validator; 

... 
violations = validator.validate(account);