I have a Spring Boot application, which uses annotations from javax.validation
to validate my domain object. Unfortunately, the error message doesn't contain the ID of the domain object. I need the ID for operation and development (debugging).
Code
@SpringBootApplication
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
@Data
static class Model {
private String id;
@Min(2)
private int number;
}
@RestController
static class Controller {
@PostMapping("/test")
public int test(@RequestBody @Valid Model model) {
return 1;
}
}
}
Logs
2022-05-12 10:39:15.252 WARN 1424 --- [nio-8080-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.bind.MethodArgumentNotValidException: Validation failed for argument [0] in public int test.TestApplication$Controller.test(test.TestApplication$Model): [Field error in object 'model' on field 'number': rejected value [1]; codes [Min.model.number,Min.number,Min.int,Min]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [model.number,number]; arguments []; default message [number],2]; default message [muss größer-gleich 2 sein]] ]
Research
I can add values of the annotation attributes and the value of the validated property, see Hibernate Validator:
4.1.2. Interpolation with message expressions
As of Hibernate Validator 5 (Bean Validation 1.1) it is possible to use the Unified Expression Language (as defined by JSR 341) in constraint violation messages. This allows to define error messages based on conditional logic and also enables advanced formatting options. The validation engine makes the following objects available in the EL context:
the attribute values of the constraint mapped to the attribute names
the currently validated value (property, bean, method parameter etc.) under the name validatedValue
a bean mapped to the name formatter exposing the var-arg method format(String format, Object... args) which behaves like java.util.Formatter.format(String format, Object... args).
I can write a custom message interpolation, but the
MessageInterpolator.Context
only provides the validated value.
Question
How can I add domain object's ID to the validation message?