I have a Person model:
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;
}
}
I have simple @RestController where I have to validate the @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;
}
}
Here is my simple Spring Config:
@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}
Also I've defined @ControllerAdvice, which simply returns all error messages from bindings:
@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());
}
}
As you can see, I've tried different variants to access messages, but, unfortunately, I am getting only the default messages.
When I send invalid data,
{
"id": 999, // valid
"name": "121", // invalid - too short
"age": -123 // invalid - negative
}
the response is:
[
"length must be between 5 and 30",
"must be greater than or equal to 0"
]
But should be:
[
"Person's age must be greater than 0",
"Person's name length should be between 5 and 30"
]
I am using:
- org.hibernate:hibernate-validator: 5.2.4.Final
- Spring Boot: 1.3.5.RELEASE
Where I am wrong?