天天看点

代码小记---hibernate参数校验,自定义枚举校验注解及消息中添加自定义参数

注解定义:

package com.example.demo.validate;

import com.alibaba.fastjson.JSON;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.EnumUtils;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.constraintvalidation.HibernateConstraintValidatorContext;
import org.springframework.util.CollectionUtils;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Target(value = {ElementType.FIELD, ElementType.PARAMETER})
@Retention(RUNTIME)
@Constraint(validatedBy = {EnumCheck.StringConstraintValidator.class})
public @interface EnumCheck {
    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    String message() default "{org.sang.enum.check}";

    Class clazz();

    String property();

    class StringConstraintValidator implements ConstraintValidator<EnumCheck, String> {
        private Set<String> allowValues = new HashSet<>();

        @Override
        public void initialize(EnumCheck constraintAnnotation) {
            Class clazz = constraintAnnotation.clazz();
            String property = constraintAnnotation.property();
            if (clazz == null || !clazz.isEnum() || StringUtils.isBlank(property)) {
                return;
            }
            List<Enum> enums = EnumUtils.getEnumList(clazz);
            if (CollectionUtils.isEmpty(enums)) {
                return;
            }
            for (Enum item : enums) {
                String value = null;
                try {
                    String enumName = item.name();
                    if (item.getClass().getField(enumName).getAnnotation(Illegal.class) != null) {
                        continue;
                    }
                    if ("Enum.name".equalsIgnoreCase(property)) {
                        value = enumName;
                    } else {
                        Object field = PropertyUtils.getProperty(item, property);
                        if (field != null) {
                            value = field.toString();
                        }
                    }
                    allowValues.add(value);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }

        @Override
        public boolean isValid(String value, ConstraintValidatorContext context) {
            HibernateConstraintValidatorContext ctxt = context.unwrap(HibernateConstraintValidatorContext.class);
            ctxt.addMessageParameter("items", JSON.toJSONString(allowValues));
            return allowValues.contains(value);
        }
    }

    @interface Illegal {
    }
}

           

申明一个枚举:

package com.example.demo.validate;

import lombok.Getter;

@Getter
public enum MyEnum {
    A("aa"),
    B("bb"),
    @EnumCheck.Illegal
    C("cc");
    private String id;

    MyEnum(String id) {
        this.id = id;
    }
}

           

测试使用注解:

package com.example.demo.validate;

import lombok.Data;
import org.hibernate.validator.HibernateValidator;

import javax.validation.Validation;
import javax.validation.Validator;

@Data
public class User {
    @EnumCheck(clazz = MyEnum.class, property = "id")
    private String id;

    public static void main(String[] args) {
        Validator validatorAll = Validation.byProvider(HibernateValidator.class).configure().failFast(false).buildValidatorFactory().getValidator();
        User user = new User();
        user.setId("123");
        System.out.println(validatorAll.validate(user));
    }
}

           

在resources下直接添加国际化文件:

ValidationMessages.properties

org.sang.enum.check=must be one of {items}
           

ValidationMessages_zh_CN.properties

org.sang.enum.check=必须是{items}之一
           

===================================================================

梦想还是要有的,万一实现了呢!