1. 程式人生 > >高效使用hibernate-validator校驗框架

高效使用hibernate-validator校驗框架

一、前言

  高效、合理的使用hibernate-validator校驗框架可以提高程式的可讀性,以及減少不必要的程式碼邏輯。接下來會介紹一下常用一些使用方式。

二、常用註解說明

限制 說明
@Null 限制只能為null
@NotNull 限制必須不為null
@AssertFalse 限制必須為false
@AssertTrue 限制必須為true
@DecimalMax(value) 限制必須為一個不大於指定值的數字
@DecimalMin(value) 限制必須為一個不小於指定值的數字
@Digits(integer,fraction) 限制必須為一個小數,且整數部分的位數不能超過integer,小數部分的位數不能超過fraction
@Future 限制必須是一個將來的日期
@Max(value) 限制必須為一個不大於指定值的數字
@Min(value) 限制必須為一個不小於指定值的數字
@Past 限制必須是一個過去的日期
@Pattern(value) 限制必須符合指定的正則表示式
@Size(max,min) 限制字元長度必須在min到max之間
@Past 驗證註解的元素值(日期型別)比當前時間早
@NotEmpty 驗證註解的元素值不為null且不為空(字串長度不為0、集合大小不為0)
@NotBlank 驗證註解的元素值不為空(不為null、去除首位空格後長度為0),不同於@NotEmpty,@NotBlank只應用於字串且在比較時會去除字串的空格
@Email 驗證註解的元素值是Email,也可以通過正則表示式和flag指定自定義的email格式

三、定義校驗分組

public class ValidateGroup {
    public interface FirstGroup {
    }

    public interface SecondeGroup {
    }

    public interface ThirdGroup {
    }
}

四、定義校驗Bean

@Validated
@GroupSequence({ValidateGroup.FirstGroup.class, BaseMessageRequestBean.class})
public class BaseMessageRequestBean {

    //渠道型別
    @NotNull(message = "channelType為NULL", groups = ValidateGroup.FirstGroup.class)
    private String channelType;

    //訊息(模板訊息或者普通訊息)
    @NotNull(message = "data為NUll", groups = ValidateGroup.FirstGroup.class)
    @Valid
    private Object data;

    //業務型別
    @NotNull(message = "bizType為NULL", groups = ValidateGroup.FirstGroup.class)
    private String bizType;

    //訊息推送物件
    @NotBlank(message = "toUser為BLANK", groups = ValidateGroup.FirstGroup.class)
    private String toUser;

    private long createTime = Instant.now().getEpochSecond();

    ......
}

  請自行參考:@Validated和@Valid區別

五、validator基本使用

@RestController
public class TestValidatorController {
    @RequestMapping("/test/validator")
    public void test(@Validated BaseMessageRequestBean bean){
        ...
    }
}

  這種使用方式有一個弊端,不能自定義返回異常。spring如果驗證失敗,則直接丟擲異常,一般不可控。

六、藉助BindingResult

@RestController
public class TestValidatorController {
    @RequestMapping("/test/validator")
    public void test(@Validated BaseMessageRequestBean bean, BindingResult result){
        result.getAllErrors();
        ...
    }
}

  如果方法中有BindingResult型別的引數,spring校驗完成之後會將校驗結果傳給這個引數。通過BindingResult控制程式丟擲自定義型別的異常或者返回不同結果。

七、全域性攔截校驗器

  當然了,需要在藉助BindingResult的前提下...

@Aspect
@Component
public class ControllerValidatorAspect {
    @Around("execution(* com.*.controller..*.*(..)) && args(..,result)")
    public Object doAround(ProceedingJoinPoint pjp, result result) {
        result.getFieldErrors();
        ...
    }
}

  這種方式可以減少controller層校驗的程式碼,校驗邏輯統一處理,更高效。

 八、藉助ValidatorUtils工具類

@Bean
public Validator validator() {
    return new LocalValidatorFactoryBean();
}

LocalValidatorFactoryBean官方示意

  LocalValidatorFactoryBean是Spring應用程式上下文中javax.validation(JSR-303)設定的中心類:它引導javax.validation.ValidationFactory並通過Spring Validator介面以及JSR-303 Validator介面和ValidatorFactory公開它。介面本身。通過Spring或JSR-303 Validator介面與該bean的例項進行通訊時,您將與底層ValidatorFactory的預設Validator進行通訊。這非常方便,因為您不必在工廠執行另一個呼叫,假設您幾乎總是會使用預設的Validator。這也可以直接注入Validator型別的任何目標依賴項!從Spring 5.0開始,這個類需要Bean Validation 1.1+,特別支援Hibernate Validator 5.x(參見setValidationMessageSource(org.springframework.context.MessageSource))。這個類也與Bean Validation 2.0和Hibernate Validator 6.0執行時相容,有一個特別說明:如果你想呼叫BV 2.0的getClockProvider()方法,通過#unwrap(ValidatorFactory.class)獲取本機ValidatorFactory,在那裡呼叫返回的本機引用上的getClockProvider()方法。Spring的MVC配置名稱空間也使用此類,如果存在javax.validation API但未配置顯式Validator。

@Component
public class ValidatorUtils implements ApplicationContextAware {

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ValidatorUtils.validator = (Validator) applicationContext.getBean("validator");
    }

    private static Validator validator;

    public static Optional<String> validateResultProcess(Object obj)  {
        Set<ConstraintViolation<Object>> results = validator.validate(obj);
        if (CollectionUtils.isEmpty(results)) {
            return Optional.empty();
        }
        StringBuilder sb = new StringBuilder();

        for (Iterator<ConstraintViolation<Object>> iterator = results.iterator(); iterator.hasNext(); ) {
            sb.append(iterator.next().getMessage());
            if (iterator.hasNext()) {
                sb.append(" ,");
            }
        }
        return Optional.of(sb.toString());
    }
}

  為什麼要使用這個工具類呢?

  1、controller方法中不用加入BindingResult引數

  2、controller方法中需要校驗的引數也不需要加入@Valid或者@Validated註解

  怎麼樣是不是又省去了好多程式碼,開不開心。

  具體使用,在controller方法或者全域性攔截校驗器中呼叫 ValidatorUtils.validateResultProcess(需要校驗的Bean) 直接獲取校驗的結果。

  請參考更多功能的ValidatorUtils工具類

九、自定義校驗器

  定義一個MessageRequestBean,繼承BaseMessageRequestBean,signature欄位需要我們自定義校驗邏輯。

@Validated
@GroupSequence({ValidateGroup.FirstGroup.class, ValidateGroup.SecondeGroup.class, MessageRequestBean.class})
@LogicValidate(groups = ValidateGroup.SecondeGroup.class)
public class MessageRequestBean extends BaseMessageRequestBean {

    //簽名信息(除該欄位外的其他欄位按照字典序排序,將值順序拼接在一起,進行md5+Base64簽名演算法)
    @NotBlank(message = "signature為BLANK", groups = ValidateGroup.FirstGroup.class)
    private String signature;
    ...
}

  實現自定義校驗邏輯也很簡單......

  1、自定義一個帶有 @Constraint註解的註解@LogicValidate,validatedBy 屬性指向該註解對應的自定義校驗器

@Target({TYPE})
@Retention(RUNTIME)
//指定驗證器  
@Constraint(validatedBy = LogicValidator.class)
@Documented
public @interface LogicValidate {
    String message() default "校驗異常";
    //分組
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

  2、自定義校驗器LogicValidator,泛型要關聯上自定義的註解和需要校驗bean的型別

public class LogicValidator implements ConstraintValidator<LogicValidate, MessageRequestBean> {

    @Override
    public void initialize(LogicValidate logicValidate) {
    }

    @Override
    public boolean isValid(MessageRequestBean messageRequestBean, ConstraintValidatorContext context) {
        String toSignature = StringUtils.join( messageRequestBean.getBizType()
                , messageRequestBean.getChannelType()
                , messageRequestBean.getData()
                , messageRequestBean.getToUser());
        String signature = new Base64().encodeAsString(DigestUtils.md5(toSignature));
        if (!messageRequestBean.getSignature().equals(signature)) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate("signature校驗失敗")
                    .addConstraintViolation();
            return false;
        }
        return true;
    }
}

  可以通過ConstraintValidatorContext禁用掉預設的校驗配置,然後自定義校驗配置,比如校驗失敗後返回的資訊。

十、springboot國際化資訊配置

@Configuration
@ConditionalOnMissingBean(value = MessageSource.class, search = SearchStrategy.CURRENT)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
@Conditional(ResourceBundleCondition.class)
@EnableConfigurationProperties
@ConfigurationProperties(prefix = "spring.messages")
public class MessageSourceAutoConfiguration {

    private static final Resource[] NO_RESOURCES = {};

    /**
     * Comma-separated list of basenames, each following the ResourceBundle convention.
     * Essentially a fully-qualified classpath location. If it doesn't contain a package
     * qualifier (such as "org.mypackage"), it will be resolved from the classpath root.
     */
    private String basename = "messages";

    /**
     * Message bundles encoding.
     */
    private Charset encoding = Charset.forName("UTF-8");

    /**
     * Loaded resource bundle files cache expiration, in seconds. When set to -1, bundles
     * are cached forever.
     */
    private int cacheSeconds = -1;

    /**
     * Set whether to fall back to the system Locale if no files for a specific Locale
     * have been found. if this is turned off, the only fallback will be the default file
     * (e.g. "messages.properties" for basename "messages").
     */
    private boolean fallbackToSystemLocale = true;

    /**
     * Set whether to always apply the MessageFormat rules, parsing even messages without
     * arguments.
     */
    private boolean alwaysUseMessageFormat = false;

    @Bean
    public MessageSource messageSource() {
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        if (StringUtils.hasText(this.basename)) {
            messageSource.setBasenames(StringUtils.commaDelimitedListToStringArray(
                    StringUtils.trimAllWhitespace(this.basename)));
        }
        if (this.encoding != null) {
            messageSource.setDefaultEncoding(this.encoding.name());
        }
        messageSource.setFallbackToSystemLocale(this.fallbackToSystemLocale);
        messageSource.setCacheSeconds(this.cacheSeconds);
        messageSource.setAlwaysUseMessageFormat(this.alwaysUseMessageFormat);
        return messageSource;
    }

    public String getBasename() {
        return this.basename;
    }

    public void setBasename(String basename) {
        this.basename = basename;
    }

    public Charset getEncoding() {
        return this.encoding;
    }

    public void setEncoding(Charset encoding) {
        this.encoding = encoding;
    }

    public int getCacheSeconds() {
        return this.cacheSeconds;
    }

    public void setCacheSeconds(int cacheSeconds) {
        this.cacheSeconds = cacheSeconds;
    }

    public boolean isFallbackToSystemLocale() {
        return this.fallbackToSystemLocale;
    }

    public void setFallbackToSystemLocale(boolean fallbackToSystemLocale) {
        this.fallbackToSystemLocale = fallbackToSystemLocale;
    }

    public boolean isAlwaysUseMessageFormat() {
        return this.alwaysUseMessageFormat;
    }

    public void setAlwaysUseMessageFormat(boolean alwaysUseMessageFormat) {
        this.alwaysUseMessageFormat = alwaysUseMessageFormat;
    }

    protected static class ResourceBundleCondition extends SpringBootCondition {

        private static ConcurrentReferenceHashMap<String, ConditionOutcome> cache = new ConcurrentReferenceHashMap<String, ConditionOutcome>();

        @Override
        public ConditionOutcome getMatchOutcome(ConditionContext context,
                AnnotatedTypeMetadata metadata) {
            String basename = context.getEnvironment()
                    .getProperty("spring.messages.basename", "messages");
            ConditionOutcome outcome = cache.get(basename);
            if (outcome == null) {
                outcome = getMatchOutcomeForBasename(context, basename);
                cache.put(basename, outcome);
            }
            return outcome;
        }

        private ConditionOutcome getMatchOutcomeForBasename(ConditionContext context,
                String basename) {
            ConditionMessage.Builder message = ConditionMessage
                    .forCondition("ResourceBundle");
            for (String name : StringUtils.commaDelimitedListToStringArray(
                    StringUtils.trimAllWhitespace(basename))) {
                for (Resource resource : getResources(context.getClassLoader(), name)) {
                    if (resource.exists()) {
                        return ConditionOutcome
                                .match(message.found("bundle").items(resource));
                    }
                }
            }
            return ConditionOutcome.noMatch(
                    message.didNotFind("bundle with basename " + basename).atAll());
        }

        private Resource[] getResources(ClassLoader classLoader, String name) {
            try {
                return new PathMatchingResourcePatternResolver(classLoader)
                        .getResources("classpath*:" + name + ".properties");
            }
            catch (Exception ex) {
                return NO_RESOURCES;
            }
        }

    }

}

  從上面的MessageSource自動配置可以看出,可以通過spring.message.basename指定要配置國際化檔案位置,預設值是“message”。spring boot預設就支援國際化的,預設會去resouces目錄下尋找message.properties檔案。

  這裡就不進行過多關於國際化相關資訊的介紹了,肯定少不了區域解析器。springboot國際化相關知識請參考:Spring Boot國際化(i18n)