在spring消息插值中使用另一个对象字段值

aoyhnmkz  于 8个月前  发布在  Spring
关注(0)|答案(1)|浏览(46)

如果可能的话,我正在尝试用一个值来定制一个约束的消息,这个值实际上不是要验证的那个值,而是属于同一个类。

public Car {
  @NotEmpty(message = The car of the model '${this.model}' requires a plate_number)
  String plate_number;

  String model;
}

现在创建了一个新的示例

Car myCar = new Car(null, Audi);

验证后,我想得到消息“型号为Audi的汽车需要车牌号码”
我不知道这是否可能。谢谢您的支持:)

xkftehaa

xkftehaa1#

我不知道@NotEmpty注解,因为你正在使用constructor创建一个Car对象,我也知道当使用javaxjakarta验证时,通常它是在暴露到REST端点的DTO上。
作为替代方案,您可以使用Assert.notNull到constructor:

public class Car {

  private String model;

  private String plate_number;

  public Car(String model, String plate_number) {
    this.model = model;
    Assert.notNull(plate_number,
        "The car of the model " + this.model + " requires a plate_number");
    this.plate_number = plate_number;
  }
}

当你经过时:

Car car = new Car("Audi", null);

在控制台中,您将看到下一条错误消息:

java.lang.IllegalArgumentException: The car of the model Audi  requires a plate_number

相关问题