遵守以下代码。DealerLot 有一个 carInventory,它由汽车组成,所有汽车都包含一个引擎。当前dealerlot 有两辆汽车在库存中,并且在验证时,汽车的一个引擎未能通过验证。但是,错误消息仅包含有关引擎的信息。在消息中包含 carName 的最干净的方法是什么?
public class main {
@Data
@AllArgsConstructor
static class Engine {
@Pattern(regexp="V.*", message="Engine Name must start with a V! You provided ${validatedValue}")
private String engineName;
}
@Data
@AllArgsConstructor
static class Car {
private String carName;
@Valid
private Engine engine;
}
@Data
@AllArgsConstructor
static class DealerLot {
@Valid
private List<Car> carInventory;
}
public static void main(String args[]){
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Engine engine1 = new Engine("VQ35DE");
Car car1 = new Car("Nissan 350z", engine1);
Engine engine2 = new Engine("2JZ-GTE");
Car car2 = new Car("Toyota Supra", engine2);
DealerLot dealerLot1 = new DealerLot(Arrays.asList(car1, car2));
Set<ConstraintViolation<DealerLot>> i = validator.validate(dealerLot1);
for (ConstraintViolation<DealerLot> v : i) {
System.out.println(v.getMessage());
};
}}
输出:
Engine Name must start with a V! You provided 2JZ-GTE
我希望输出看起来像下面这样:
Toyota Supra, Engine Name must start with a V! You provided 2JZ-GTE
如果没有这种清晰程度,确定哪些汽车有问题可能会非常混乱。
仅供参考,这些是我在示例中使用的依赖项的版本:
compile group: 'org.hibernate.validator', name: 'hibernate-validator', version: '6.0.17.Final'
compile group: 'org.glassfish', name: 'javax.el', version: '3.0.1-b11'
implementation group: 'org.projectlombok', name: 'lombok', version: "1.18.4"
compile group: 'javax.validation', name: 'validation-api', version: '2.0.1.Final'