使用bean验证来验证对象的状态时,只要调用验证,就会调用带有@AssertTrue
注释的方法4次。它应该只在每次调用时调用一次。
Hibernate-validator版本:5.1.3.Final
以下是一个例子:
对于以下类摩托车:
import javax.validation.constraints.AssertTrue;
class Motorcycle{
private int fuel;
private int tireDurability;
@AssertTrue(message = "motorcycle.not.available.to.use")
public boolean isAvailable(){
return fuel > 0 && tireDurability > 0;
}
public void toUse(){...}
}
主要:
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
public class Main{
public static void main(String []args){
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<Motorcycle>> violations = validator.validate(new Motorcycle());
}
}
调用validator.validate(new Motorcycle())
时,方法isAvailable()
将被调用4次。
任何人都可以帮我解决这个问题吗?这是一个错误吗?我该如何解决这个问题?
答案 0 :(得分:2)
您应该尝试使用Hibernate Validator 6.0.2.Final(它目前是最新的可用版本)。下一个测试确实通过了验证器的这个(最新)版本:
@Test
public void testMotorcycle() throws Exception {
AtomicInteger count = new AtomicInteger( 0 );
Motorcycle motorcycle = new Motorcycle( count );
validator.validate( motorcycle );
assertEquals( motorcycle.count.get(), 1 );
}
class Motorcycle {
final AtomicInteger count;
private int fuel;
private int tireDurability;
Motorcycle(AtomicInteger count) {
this.count = count;
}
@AssertTrue(message = "motorcycle.not.available.to.use")
public boolean isAvailable() {
count.incrementAndGet();
return fuel > 0 && tireDurability > 0;
}
}
我确实尝试用5.1运行它 - 它也通过那里。您是如何确定该方法被调用4次的?