2012-10-17 86 views
1

驗證有問題。是否可以使用一個ConstraintValidator來驗證bean的兩個屬性?我有類似如下:jsr303驗證2個屬性只有一個自定義驗證程序

@Component 
public class CheckSomeBeanPropertiesValidator implements ConstraintValidator<CheckSomeBeanProperties, SearchFormBean> { 

@Autowired 
SomeApplicationService applicationService; 

public void initialize(CheckSomeBeanProperties checkSomeBeanProperties) { 
} 

public boolean isValid(SearchFormBean searchFormBean, ConstraintValidatorContext context) { 

ReturnSearchBean searchBean = applicationService.findBySearchBean(searchFormBean); 

if(searchBean.isNoResults()) return false; // it will return the message No data found 

if(searchBean.isTooManyDataReturned()) return false; // it will return too many records found 

return true; 
} 
} 

的CheckSomeBeanPropertiesValidator我調用服務SomeApplicationService返回一些數據中搜索調用findBySearchBean內。相反,必須調用多個自定義的ConstraintValidator(以及多個findBySearchBean),是否可以只調用一次該服務並檢查兩個不同的屬性?

感謝

再見

+0

您的問題是相當模糊的,你也應該張貼你如何使用您的自定義約束的代碼。我只是猜測你在兩個不同的屬性上使用了這個自定義約束,但你只想擁有一次。這隻有在您使用類級別約束時纔有可能。再說,我只是猜測:-) – Hardy

+0

嗨,我使用它的一流水平,如:@CheckSomeBeanPropertiesValidator 公共類SearchFormBean實現Serializable {布爾noResults; boolean tooManyDataReturned; ....}但問題是,我想根據bean的哪個布爾值爲true來返回兩個不同的消息。我不想驗證兩個不同的屬性調用兩次相同的服務findBySearchBean。謝謝你, – user1079272

回答

0

如果你想改變依賴於驗證結果的錯誤信息,你應該使用ConstraintValidatorContext。您可以禁用默認錯誤信息並自行構建。例如:

constraintContext.disableDefaultConstraintViolation(); 
constraintContext.buildConstraintViolationWithTemplate("{mykey}" ).addConstraintViolation(); 

您還可以調整約束違規的屬性路徑。 ConstraintValidatorContext提供流暢的API。只是檢查的Javadoc或與您的IDE探索:-)

+0

非常感謝!我會很快嘗試你的解決方案。再見 – user1079272

相關問題