Java springconverter、Validator和DataBinder:如何单独处理多值bean字段?

Java springconverter、Validator和DataBinder:如何单独处理多值bean字段?,java,spring,spring-boot,spring-mvc,Java,Spring,Spring Boot,Spring Mvc,我有一个bean,其中有一个List类型的字段 public List<MyClass> getter() { return field; } public void setter(MyClass[] source) { this.field = Arrays.asList(source); } 而我更喜欢 Field has invalid value of "invalid" 换言之,如何使转换和验证在每个值上单独工作 尽管spring的方法

我有一个bean,其中有一个List类型的字段

  public List<MyClass> getter() {
    return field;
  }

  public void setter(MyClass[] source) {
    this.field = Arrays.asList(source);
  }
而我更喜欢

Field has invalid value of "invalid"

换言之,如何使转换和验证在每个值上单独工作

尽管spring的方法不是很聪明,但在逻辑上是正确的。以下代码可以帮助您找到无效值

            FieldError fieldError = bindingResult.getFieldError();
            if (fieldError != null && fieldError.contains(TypeMismatchException.class)) {
                TypeMismatchException typeMismatchException = fieldError.unwrap(TypeMismatchException.class);
                ConversionFailedException conversionFailedException = findConversionFailedException(typeMismatchException);
                if (conversionFailedException != null) {
                    Object value = conversionFailedException.getValue();
                    // get the invalid field value
                }
            }
            FieldError fieldError = bindingResult.getFieldError();
            if (fieldError != null && fieldError.contains(TypeMismatchException.class)) {
                TypeMismatchException typeMismatchException = fieldError.unwrap(TypeMismatchException.class);
                ConversionFailedException conversionFailedException = findConversionFailedException(typeMismatchException);
                if (conversionFailedException != null) {
                    Object value = conversionFailedException.getValue();
                    // get the invalid field value
                }
            }
    /**
     * Recursively find the ConversionFailedException
     * @param target
     * @return
     */
    public ConversionFailedException findConversionFailedException(Throwable target) {
        Throwable cause = target.getCause();
        if (cause == null) {
            return null;
        } else if (cause instanceof ConversionFailedException) {
            return (ConversionFailedException)cause;
        }
        return findConversionFailedException(target);
    }