springboot中参数校验(validation)注解自定义

缺乏、安全感 2022-03-19 11:17 578阅读 0赞

在进行参数验证的时候,往往存在现有的约束注解不能满足的情况,此时就需要我们自己定义validation注解了,下面来介绍一下如何自己定义一个验证注解。

有关参数校验的使用可详见《springboot中参数校验(validation)使用》

如何自定义一个validation注解?

自己定义validation注解需要使用@Constraint。@Constraint注解中是这样进行描述的:

  1. * Marks an annotation as being a Bean Validation constraint.
  2. * <p/>
  3. * A given constraint annotation must be annotated by a { @code @Constraint}
  4. * annotation which refers to its list of constraint validation implementations.
  5. * <p/>
  6. * Each constraint annotation must host the following attributes:
  7. * <ul>
  8. * <li>{ @code String message() default [...];} which should default to an error
  9. * message key made of the fully-qualified class name of the constraint followed by
  10. * { @code .message}. For example { @code "{com.acme.constraints.NotSafe.message}"}</li>
  11. * <li>{ @code Class<?>[] groups() default { };} for user to customize the targeted
  12. * groups</li>
  13. * <li>{ @code Class<? extends Payload>[] payload() default { };} for
  14. * extensibility purposes</li>
  15. * </ul>
  16. * <p/>

可以看出,@Constraint用其来标注我们的注解是一个验证注解(Validation constraint),同时还指明了我们在自己定义验证注解的时候不可缺少的三个注解元素:

  1. String message() default [...];
  2. Class<?>[] groups() default { };
  3. Class<? extends Payload>[] payload() default { };

自定义validation注解的时候,不仅要写出一个满足我们要求的注解,好需要搭配一个验证实现(validator),实现如下接口:

  1. javax.validation.ConstraintValidator

自定义validation注解案例

枚举验证注解@Enum

validation-api的注解和hibernate的扩展中没有对枚举值验证的注解,而在有些时候枚举值验证又是需要的,下面我们来自己定义这样一个validation注解,代码如下:

  1. package com.lazycece.sbac.validation.constraint;
  2. import com.lazycece.sbac.validation.constraint.validator.EnumValidator;
  3. import javax.validation.Constraint;
  4. import javax.validation.Payload;
  5. import java.lang.annotation.Documented;
  6. import java.lang.annotation.Repeatable;
  7. import java.lang.annotation.Retention;
  8. import java.lang.annotation.Target;
  9. import static java.lang.annotation.ElementType.*;
  10. import static java.lang.annotation.ElementType.PARAMETER;
  11. import static java.lang.annotation.ElementType.TYPE_USE;
  12. import static java.lang.annotation.RetentionPolicy.RUNTIME;
  13. /** * @author lazycece * @date 2019/2/15 */
  14. @Documented
  15. @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})
  16. @Retention(RUNTIME)
  17. @Repeatable(Enum.List.class)
  18. @Constraint(validatedBy = { EnumValidator.class})
  19. public @interface Enum {
  20. String message() default "{*.validation.constraint.Enum.message}";
  21. Class<?>[] groups() default { };
  22. Class<? extends Payload>[] payload() default { };
  23. /** * the enum's class-type * * @return Class */
  24. Class<?> clazz();
  25. /** * the method's name ,which used to validate the enum's value * * @return method's name */
  26. String method() default "ordinal";
  27. /** * Defines several {@link Enum} annotations on the same element. * * @see Enum */
  28. @Documented
  29. @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})
  30. @Retention(RUNTIME)
  31. @interface List {
  32. Enum[] value();
  33. }
  34. }

枚举验证注解validator

注解验证逻辑的validator代码如下,通过反射方式获取枚举的值进行判断。

  1. package com.lazycece.sbac.validation.constraint.validator;
  2. import com.lazycece.sbac.validation.constraint.Enum;
  3. import javax.validation.ConstraintValidator;
  4. import javax.validation.ConstraintValidatorContext;
  5. import java.lang.reflect.Method;
  6. /** * @author lazycece * @date 2019/2/15 */
  7. public class EnumValidator implements ConstraintValidator<Enum, Object> {
  8. private Enum annotation;
  9. @Override
  10. public void initialize(Enum constraintAnnotation) {
  11. this.annotation = constraintAnnotation;
  12. }
  13. @Override
  14. public boolean isValid(Object value, ConstraintValidatorContext context) {
  15. if (value == null) {
  16. return false;
  17. }
  18. Object[] objects = annotation.clazz().getEnumConstants();
  19. try {
  20. Method method = annotation.clazz().getMethod(annotation.method());
  21. for (Object o : objects) {
  22. if (value.equals(method.invoke(o))) {
  23. return true;
  24. }
  25. }
  26. } catch (Exception e) {
  27. throw new RuntimeException(e);
  28. }
  29. return false;
  30. }
  31. }

使用方式

@Enum注解的使用需要给出枚举类和获取需要验证的枚举值的方法(默认情况下是ordinal)。

如果我们定义的枚举类如下所示,那么在验证的时候会设计到四种方式的验证:

  1. package com.lazycece.sbac.validation.enums;
  2. /** * @author lazycece * @date 2019/02/15 */
  3. public enum Role {
  4. ADMIN(1, "ADMIN"),
  5. TEST(2, "TEST"),
  6. DEVELOP(3, "DEVELOP");
  7. private int value;
  8. private String desc;
  9. Role(int value, String desc) {
  10. this.value = value;
  11. this.desc = desc;
  12. }
  13. public int getValue() {
  14. return value;
  15. }
  16. public void setValue(int value) {
  17. this.value = value;
  18. }
  19. public String getDesc() {
  20. return desc;
  21. }
  22. public void setDesc(String desc) {
  23. this.desc = desc;
  24. }
  25. }
  • 参数param为枚举的ordinal值

    1. @Enum(clazz = Role.class, message = "role参数错误")
  • 参数param为枚举的name值

    1. @Enum(clazz = Role.class, method = "name", message = "role参数错误")
  • 参数param为枚举的value值

    1. @Enum(clazz = Role.class, method = "getValue", message = "role参数错误")
  • 参数param为枚举的desc值

    1. @Enum(clazz = Role.class, method = "getDesc", message = "role参数错误")

案例源码

案例源码地址:https://github.com/lazycece/springboot-actual-combat/tree/master/springboot-ac-validation

发表评论

表情:
评论列表 (有 0 条评论,578人围观)

还没有评论,来说两句吧...

相关阅读