Spring JSR-303 ConstraintValidator 不支持 list.add()

Spring JSR-303 ConstraintValidator not support list.add()

我遇到过这样的误会: 我使用自己的注释 @Category 和 class CategoryValidator implements ConstraintValidator<Category, String>

进行了验证

一切都是关于 list.add() 的,这会导致(没有它正常工作):

Request processing failed; nested exception is javax.validation.ValidationException: HV000028: Unexpected exception during isValid call.

谁能给我解释一下?

类别验证器

@Component
public class CategoryValidator implements ConstraintValidator<Category, String> {

@Autowired
ProductService productService;

List<String> allowedCategories;

@Override
public void initialize(Category constraintAnnotation) {
    allowedCategories = Arrays.asList(constraintAnnotation.allowedCategories());
}

@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
    // This .add() it not working here
    // allowedCategories.add("Laptop"); 

    for (String category : allowedCategories) {
        if (category.equalsIgnoreCase(value)) {
            return true;
        }
    }
    return false;
}
}

类别

@Target( { METHOD, FIELD, ANNOTATION_TYPE})
@Retention(RUNTIME)
@Constraint(validatedBy = CategoryValidator.class)
@Documented
public @interface Category {
String message() default "{com.ehr.webstore.validator.Category.message}";

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

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

String[] allowedCategories();
}

产品

public class Product {
/* [...] */
@Category(allowedCategories = {"Laptop", "Tablet", "Smart Phone", "Another"})
private String category;
/* [...] */
}

嗯,完整的堆栈跟踪会更容易,但我认为你的问题是你不能将元素添加到 Arrays.asList() 创建的 List:它是不可变的。

如果您希望能够添加新元素,您需要执行以下操作:new ArrayList<>( Arrays.asList( ... ) )