Car.java的代码片段如下:
@Size(min = 2, max = 14, message = "The license plate '${validatedValue}' must be between {min} and {max} characters long")
private String licensePlate;
@Min(value = 2, message = "There must be at least {value} seat${value > 1 ? 's' : ''}")
private int seatCount;
@DecimalMax(value = "350", message = "The top speed ${formatter.format('%1$.2f', validatedValue)} is higher "
+ "than {value}")
private double topSpeed;
CarTest.java的代码片段如下:
@Test
public void licensePlateTest()
{
Car car = new Car( null, "A", 1, 400.123456, BigDecimal.valueOf( 200000 ) );
String message = validator.validateProperty( car, "licensePlate" )
.iterator()
.next()
.getMessage();
assertEquals(
"The license plate must be between 2 and 14 characters long",
message
);
}
@Test
public void seatCountTest()
{
Car car = new Car( null, "A", 1, 400.123456, BigDecimal.valueOf( 200000 ) );
String message = validator.validateProperty( car, "seatCount" ).iterator().next().getMessage();
assertEquals( "There must be at least 2 seats", message );
}
licensePlate 的验证邮件是:"车牌' $ {validatedValue}'长度必须在2到14个字符之间。"
seatCount 的验证邮件是:"必须至少有2个座位$ {value> 1? ' S' :''}。"
我们可以看到,EL表达式无效。关于我的项目的pom.xml是:
<!-- Hibernate Validator -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.3.1.Final</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.el</artifactId>
<version>2.2.4</version>
</dependency>
我不知道为什么它不工作,有人可以帮助我吗?感谢。
答案 0 :(得分:3)
您使用的是Hibernate Validator 4.x版本,该版本与Bean Validation 1.0一致。在4.x版本中,使用表达式语言(EL)的变量插值不可用。这是添加到Bean Validation 1.1的功能,因此可以在Hibernate Validator 5.x系列中使用。最新的稳定版本是5.1.3.Final。我建议你升级到那个版本。
答案 1 :(得分:1)
在hibernate 4.3中,您需要将ValueFormatterMessageInterpolator指定为消息插值器,而不是使用默认值来插值$ {validatedValue}:
Configuration<?> configuration = Validation.byDefaultProvider().configure();
ValidatorFactory factory = configuration
.messageInterpolator(new ValueFormatterMessageInterpolator(configuration.getDefaultMessageInterpolator()))
.buildValidatorFactory();
Validator validator = factory.getValidator();