ehr
ehr

Reputation: 153

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

I've met such a misundestrood: I've made a validation using my own annotation @Category and class CategoryValidator implements ConstraintValidator<Category, String>

All is about list.add() which causes (without it works properly):

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

Can someone give me any explaination?

CategoryValidator

@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;
}
}

Category

@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();
}

Product

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

Upvotes: 0

Views: 85

Answers (1)

Guillaume Smet
Guillaume Smet

Reputation: 10519

Well, it would be easier with the full stacktrace but I think your issue is that you can't add an element to a List created by Arrays.asList(): it is immutable.

If you want to be able to add new elements, you need to do something like: new ArrayList<>( Arrays.asList( ... ) ).

Upvotes: 2

Related Questions