当前位置:网站首页>Personal best practice demo sharing of enum + validation

Personal best practice demo sharing of enum + validation

2022-07-07 17:59:00 Buffalo calf

Enum + Validation Personal best practices demo Share

Preface

In many scenarios, we need to verify whether the parameters passed from the front end belong to a Enum value , Share a personal best practice demo

  • Enum The simplest statement of
  • @OfEnum & OfEnumValidator
  • Test suite

Enum Statement

Usually Enum The declaration of is mapped to the corresponding DB Field , Personal practice is directly based on Enum Name Corresponding to specific value , No need to Enum It contains interpretation information, etc , such as SexEnum Declare as man woman Not like male ("man") Woman ("woman"), This is also convenient for follow-up Validator Class writing

public enum SexEnum {
    

    man
    , woman
    ;

}

@OfEnum

@Constraint(
        validatedBy = {
     OfEnumValidator.class }
)
@Target({
    ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
public @interface OfEnum {
    

    Class<?> enumType();

    String message() default " The target value must be  ${enumType.simpleName}  Enumeration value of type ";

    Class<?>[] groups() default {
    };

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

}

This annotation is mainly used for fields 、 The corresponding OfEnumValidator Perform verification

  • @Constraint Annotation declaration corresponds to OfEnumValidator
  • attribute enumType Declare the corresponding enumeration type
  • message I quote EL The expression outputs reasonable verification information

OfEnumValidator

public class OfEnumValidator implements ConstraintValidator<OfEnum, String> {
    

    private List<String> enums;

    //  Enumeration value initialization 
    @Override
    public void initialize(OfEnum constraintAnnotation) {
    
        enums = Optional.ofNullable(constraintAnnotation)
                .map(OfEnum::enumType)
                .filter(Class::isEnum)
                .map(Class::getEnumConstants)
                .map(arr -> Arrays.stream(arr)
                        .map(Object::toString)
                        .collect(Collectors.toList()))
                .orElse(new ArrayList<>());
    }

    @Override
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
    

        return !ObjectUtils.isEmpty(enums) && enums.contains(s);
    }
}

OfEnumValidator Class is responsible for executing @OfEnum The verification corresponding to the annotation

  • Initialize based on the specified enumeration class enums attribute , Based on the direct toString Method , Therefore, I recommend Enum Simple statement of
  • isValid check

Test

public class OfEnumTest {
    

    ApplicationContextRunner runner = new ApplicationContextRunner()
            .withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class));

    @Validated
    static class Handler {
    

        public void handle(@OfEnum(enumType = SexEnum.class) String sex) {
    

        }
    }

    static class Config {
    

        @Bean
        public Handler handler() {
    
            return new Handler();
        }
    }

    @Test
    public void test() {
    
        runner.withUserConfiguration(Config.class)
                .run(context -> {
    
                    Handler bean = context.getBean(Handler.class);
                    bean.handle("man");
                    assertThatThrownBy(() -> bean.handle("error"))
                            .isInstanceOf(ConstraintViolationException.class)
                            .hasMessage("handle.sex:  The target value must be  SexEnum  Enumeration value of type ");
                });
    }
}

in the light of @OfEnum Annotated test class :

  • be based on ApplicationContextRunner To write , Good test helper class , There was sharing before
  • You can see , When it comes to SexEnum Values other than members , A verification exception will be thrown

summary

The above is a person Enum + Validation Best practices sharing

原网站

版权声明
本文为[Buffalo calf]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207071521237350.html