我正在尝试从属性文件获取自定义错误消息显示。尽管我正在仔细阅读Hibernate 6的在线指南,并且验证程序确实起作用,但是它们提供的示例并未显示自定义错误。我尝试将属性文件中的类重命名为“ Car”而不是“ car”,并尝试了不同的错误类,例如Min或Max,但始终会显示默认错误消息。我怀疑属性文件的格式或命名存在问题,但我不知道应如何设置格式。 主班:
package fieldConstraints;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator;
import org.hibernate.validator.resourceloading.PlatformResourceBundleLocator;
import methodParameterConstraints.RentalStation;
public class Main {
public static void main(String[] args) {
//An instance of validator is created, with the custom message resource included
Validator validator = Validation.byDefaultProvider().configure()
.messageInterpolator(
new ResourceBundleMessageInterpolator(new PlatformResourceBundleLocator("MyMessages.properties")))
.buildValidatorFactory().getValidator();
Car Accord = new Car();
//A null value is applied to the licensePlate variable
Set<ConstraintViolation<Car>> violations = validator.validateValue(
Car.class,
"licensePlate",
null
);
//When getting the error message it will still display the default.
for(ConstraintViolation<Car> violation : violations){
System.out.println(violation.getMessage());
}
System.out.println(Accord.toString());
}
}
汽车类别:
package fieldConstraints;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class Car {
//For this class, the basic class variables are annotated with constraints so that when
//an instance is created , it must abide by these parameters.
@NotNull
private String manufacturer;
public Car() {
//default constructor
}
@NotNull
@Size(min = 2, max = 14)
//Constraints can be applied to fields of any access type (public, private etc.). Constraints on static fields are not supported, though.
private String licensePlate;
@Min(2)
@Max(6)
private int seatCount;
public Car(String manufacturer, String licencePlate, int seatCount) {
this.manufacturer = manufacturer;
this.licensePlate = licencePlate;
this.seatCount = seatCount;
}
//Contructors, getters setters...
}
MyMessages.properties文件:
Size.car.licensePlate = custom message here.
Min.car.seatCount = custom message: min 2 seats.
Max.car.seatCount = custom message: max 6 seats.
NotNull.car.manufacturer = custom message: manufacturer can't be null.
答案 0 :(得分:1)
要在休眠状态下设置自定义消息,请尝试使用注释中的“消息”字段。
例如:
@NotNull(message = "licensePlate cannot be null."
@Size(min = 2, max = 14, message = "Size of licensePlate needs to be between 2 and 14.")
private String licensePlate;