0
我有一個Person模型:春天Hibernate的驗證消息
public class Person {
@Min(1)
private Integer id;
@Length(min = 5, max = 30)
@NotEmpty(message = "{NotEmpty.person.name}")
private String name;
@Min(value = 0, message = "Min.person.age")
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
我有簡單@RestController
在那裏我有驗證@RequestBody
:
@RestController
public class PeopleController {
private List<Person> people = new ArrayList<>();
@RequestMapping(method = RequestMethod.POST)
public List<Person> add(@Valid @RequestBody Person person) {
people.add(person);
return people;
}
}
這裏是我的簡單的Spring配置:
@Configuration
public class Configuration {
@Bean
public MessageSource messageSource() {
final ResourceBundleMessageSource source = new ResourceBundleMessageSource();
source.setBasename("messages");
return source;
}
@Bean
public Validator validator(MessageSource messageSource) {
final LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
validator.setValidationMessageSource(messageSource);
return validator;
}
}
messages.properties:
Min.person.age=Person's {0} must be greater than {1}
NotEmpty.person.name=Person's {0} cannot be empty
NotNull.person.name=Person's {0} cannot be null
Length.person.name=Person's {0} length should be between {1} and {2}
而且我定義@ControllerAdvice
,它只是返回從綁定的所有錯誤消息:
@ControllerAdvice
public class ErrorHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public List<String> processValidationError(MethodArgumentNotValidException ex) {
return ex.getBindingResult()
.getFieldErrors()
.stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage)
.collect(Collectors.toList());
}
}
正如你所看到的,我已經嘗試過不同的變種來訪問的消息,但不幸的是,我只獲取默認消息。
當我發送無效數據,
{
"id": 999, // valid
"name": "121", // invalid - too short
"age": -123 // invalid - negative
}
的迴應是:
[
"length must be between 5 and 30",
"must be greater than or equal to 0"
]
但應該是:
[
"Person's age must be greater than 0",
"Person's name length should be between 5 and 30"
]
我使用:
- org.hibernate作爲:休眠-驗證:5.2.4.Final
- 春季啓動:1.3.5.RELEASE
我哪裏錯了?
看到了這個問題,它可以幫助你http://stackoverflow.com/questions/7093468/how-to-add-custom-error-messages-in-hibernate-validator –
我還具有同樣的問題,你有沒有解決它,如果是的話,請告訴我如何去做。 – karthi
@karthi嗨。找到解決問題的以下存儲庫:https://github.com/ITsvetkoFF/Kv-014 –