我正在使用 javax.validation.Validation 来验证 jpa 实体。我总是针对相同的实体进行验证。
我想知道是否最好使用一个验证器进行所有验证,或者每次验证时都实例化一个新的验证器。
同样,每次我想使用它时实例化一个新的验证器在计算方面的成本是多少?
选项1:为每个验证实例化新的验证器。
public class Validator
{
public static void main(String[] args)
{
//Validation1
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Entity entityToValidate = new Entity();
entityToValidate.setEmail("NOT_A_VALID_EMAIL@@@tomanyat.com");
Set<ConstraintViolation<T>> constraintViolations = validator.validate(entityToValidate);
//Validation2 (Note that validator has been created yet a second time !! )
Validator validator2 = factory.getValidator();
Entity entityToValidate2 = new Entity();
entityToValidate.setEmail("NOT_A_VALID_EMAIL@@@tomanyat.com");
Set<ConstraintViolation<T>> constraintViolations2 = validator2.validate(entityToValidate);
}
}
选项 2:所有验证的单个验证器。
public class Validator
{
public static void main(String[] args)
{
//Validator created only once
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
//Validation #1
Entity entityToValidate = new Entity();
entityToValidate.setEmail("NOT_A_VALID_EMAIL@@@tomanyat.com");
Set<ConstraintViolation<T>> constraintViolations = validator.validate(entityToValidate);
//Validation #2
Entity entityToValidate2 = new Entity();
entityToValidate.setEmail("NOT_A_VALID_EMAIL@@@tomanyat.com");
Set<ConstraintViolation<T>> constraintViolations2 = validator .validate(entityToValidate);
}
}