如何在地图中验证集合 [英] Howto validate Collections in Maps

查看:87
本文介绍了如何在地图中验证集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对JSR-303的@Valid注释有问题. 注释适用于普通列表或集合,但我正在尝试验证包含列表的地图,即

I have a problem with the @Valid annotation of JSR-303. The annotation works fine for normal lists or and sets, but I am trying to validate Maps which contain Lists, i.e.

@Valid
HashMap<String, ArrayList<Object1>> map;

在这种情况下,不会验证Object1类的实例.是否有一种方便的方法可以递归执行此操作,而无需遍历每个对象并手动对其进行验证?

In this case, instances of Object1 class are not validated. Is there a convenient way to do this recursively, without iterating over every object and validating it manually?

推荐答案

当地图值本身是列表时,规范未指定验证行为.

The specification does not specify the validation behavior when the map values are themselves lists.

来自 JSR 303规范:

验证迭代器提供的每个对象.对于Map,该值 每个Map.Entry都经过验证(密钥未经验证).

Each object provided by the iterator is validated. For Map, the value of each Map.Entry is validated (the key is not validated).

由于您的情况下的值是一个列表,没有@Valid批注,因此不会对其进行处理.要解决此问题,您可以:

Since the value in your case is a list, which does not have a @Valid annotation, it does not get processed. To get around this you can either:

将包含的列表包装到另一个bean中,强制对列表进行批注处理.

Wrap the contained list in another bean, forcing the annotation processing onto the list.

public class ListHolder<T extends Iterable> {
    @Valid
    public T wrappedList;
}

或者,您也可以编写自定义验证器到处理您的复杂地图.像这样:

Or alternatively you can write a custom validator to handle your complex maps. Something like this:

@Target({ METHOD, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = ValidMapValidator.class)
public @interface ValidMap {
   String message() default "valid.map";

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

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

public class ValidMapValidator implements
      ConstraintValidator<ValidMap, Map<?, ?>> {

   @Override
   public void initialize(final ValidMap annotation) {
      return;
   }

   @Override
   public boolean isValid(final Map<?, ?> map,
         final ConstraintValidatorContext context) {
      if (map == null || map.size() == 0)
         return true;

      // Iterate each map entry and validate
      return true;
   }
}

这篇关于如何在地图中验证集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆