java – Hibernate Validator EL表达式不起作用
作者:互联网
我写了一个关于Hibernate Validator的简单例子,参考官方文档.
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>
我不知道为什么它不起作用,有人可以帮助我吗?谢谢.
解决方法:
您正在使用Hibernate Validator 4.x版本,该版本与Bean Validation 1.0一致.在4.x版本中,使用表达式语言(EL)的变量插值不可用.这是添加到Bean Validation 1.1的功能,因此可以在Hibernate Validator 5.x系列中使用.最新的稳定版本是5.1.3.Final.我建议你升级到那个版本.
标签:java,hibernate,hibernate-validator 来源: https://codeday.me/bug/20190628/1317877.html