为什么 Spring Boot 中没有替换验证消息?

Why a validation message is not replaced in Spring Boot?

现在我使用 Spring Boot.

开发了 REST API

我尝试验证路径参数并使用这样的自定义消息处理异常。

FooController.java

@Validated
@RestController
@RequiredArgsConstructor
public class FooController {

  private final BarService service;

  @GetMapping(value = "/test/{id}")
  public void invoke(@PathVariable @Digits(integer = 10, fraction = 0, message = "{message}") Long id) {
    service.get(id);
    ...
  }
}

ApiExceptionHandler.java

@RestControllerAdvice
@RequiredArgsConstructor
public class ApiExceptionHandler {

  @ExceptionHandler(ConstraintViolationException.class)
  public ResponseEntity<Object> handleConstraintViolationException(ConstraintViolationException exception) {
    Map<String, String> messages = new HashMap<>();
    for (ConstraintViolation violation : exception.getConstraintViolations()) {
      messages.put("message", violation.getMessage());
    }
    return new ResponseEntity<>(messages, HttpStatus.BAD_REQUEST);
  }
}

ValidationMessages.properties

message={0} must not be more than {integer} digits

当我调用这个API超过10个数字时(例如[GET /test/12345678901])发生400错误。

我的预期反应是

{
  message : id must not be more than 10 digits
}

但是,实际响应是

{
  message : {0} must not be more than 10 digits
}

所以,我的问题是 "Why a validation message is not replaced"。

如果这种方法是错误的,那么有什么方法可以得到预期的响应吗?

感谢您阅读我的问题。

附录 使用的 Spring 引导版本是 2.1.1

必须使用${validatedValue}获取消息中的参数:

message=${validatedValue} must not be more than {integer} digits

请在文档中找到有关消息插值的更多信息:

https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/?v=6.1#section-interpolation-with-message-expressions