Java 如何使用注释获取JSR303验证的message属性中写入的消息
我的设想是: 我有一个带有JSR303验证的pojo类,如下所示:Java 如何使用注释获取JSR303验证的message属性中写入的消息,java,spring,bean-validation,Java,Spring,Bean Validation,我的设想是: 我有一个带有JSR303验证的pojo类,如下所示: public class Customer{ String customerId; String name; BigDecimal salary; @NotNull(message = "CustomerId is mandatory") @Size(max = 7, message = "Invalid length for custome
public class Customer{
String customerId;
String name;
BigDecimal salary;
@NotNull(message = "CustomerId is mandatory")
@Size(max = 7, message = "Invalid length for customerId")
public void getCustomerId(){
return customerId;
}
@NotNull(message = "Name is mandatory")
public void getName(){
return name;
}
@Digits(integer=5, fraction=3, message="Invalid length for salary")
public void getSalary(){
return salary;
}
}
我的要求是,我想知道哪个特定字段未通过验证,并且我希望消息写入消息属性中
目前,我能够跟踪字段名,但无法跟踪消息属性中存在的消息
我使用以下方法
public void validateCustomer(Customer customer){
Errors errors = this.errorFactory.getInstance(Customer,
Customer.class.getName());
jsrValidator.validate(customer, errors);
if(errors.hasErrors()){
if(errors.getFieldError() != null){
//fieldName that failed to validate.
String fieldName = errors.getFieldError().getField();
//I also want the message written in the attribute
"message" of the annotation.
}
}
}
我还希望消息写入注释的属性消息中。我怎样才能得到它?可以这样做吗?什么是jsrValidator?我认为它应该是一个验证程序的实例,并且有一个验证。。。方法返回一个集合。消息应该在每个ConstraintViolation实例上都可用。是的,它是Validator的一个实例。来自org.springframework.validation.Validator;好的,让我也试试。你需要使用javax.validation.Validator。Spring版本是在应用程序的任何一层进行验证的通用方法;它与JavaBeans验证框架JSR-303无关。是的,我得到了我所需要的!多谢!