美文网首页
JSR-303 Validation 实战样例

JSR-303 Validation 实战样例

作者: liuliuzo | 来源:发表于2020-11-12 23:18 被阅读0次

Maven Dependency

  <!-- JSR 303 Validation -->
        <dependency>
            <groupId>org.hibernate.validator</groupId>
            <artifactId>hibernate-validator</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
        </dependency>
  <!-- JSR 303 Validation End -->

Samples

package com.liuliu.learning;

import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import org.hibernate.validator.HibernateValidator;
import org.hibernate.validator.messageinterpolation.ParameterMessageInterpolator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/** 
 * @className ParamValidator
 * @author: liuliu
 * @date:Jun 21, 2019 9:34:30 AM
 * @since JDK 1.8
 * 
 */
@Component
public class ParamValidator {

    private static Logger logger = LoggerFactory.getLogger(ParamValidator.class);

    /**
     * Enable fail fast, which will improve performance
     */
    private ValidatorFactory factory = Validation.byProvider(HibernateValidator.class).configure()
            .messageInterpolator(new ParameterMessageInterpolator()).failFast(true)
            .buildValidatorFactory();

    /**
     * When fail fast is enabled the validation will stop on the first constraint
     * violation detected,
     * then throw ParamSyncException with errorMsg Field.
     */
    public void validate(Object candidate) {
        Validator validator = factory.getValidator();
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(candidate);
        constraintViolations.forEach(violation -> {
            logger.debug("Field: {}, Message: {}", violation.getPropertyPath(), violation.getMessage());
            String errorMsg = violation.getPropertyPath() + ":" + violation.getMessage();
            throw new MyException(errorMsg);
        });
    }

}
  @Autowired
  private ParamValidator paramValidator;
  paramValidator.validate(candidate);

相关文章

网友评论

      本文标题:JSR-303 Validation 实战样例

      本文链接:https://www.haomeiwen.com/subject/ropmbktx.html