I'm trying to use annotation validation, but it's not working. Here's my Service Interface where I'm applying the validation:
package com.tehras.web.service;
import com.tehras.web.annotations.ValidCategory;
import com.tehras.web.models.MenuCategory;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import javax.validation.Valid;
import java.util.List;
/**
* Created by Taras on 6/17/2014.
*/
@Validated
@Service
public interface IMenuCategoriesService {
/*
@Return List<MenuCategory>
*/
public List<MenuCategory> getMenuCategories();
/*
@Return boolean
*/
public boolean addMenuCategory(@ValidCategory MenuCategory menuCategory);
/*
@Return boolean
*/
public boolean removeMenuCategories(List<MenuCategory> menuCategoryList);
public boolean containsCategoryName(String categoryName);
}
And here's my Validation class
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = {ValidCategoryImpl.class, ValidCategoryNameImpl.class})
public @interface ValidCategory {
String message() default "This Category Does not Seem to Allowed";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}
And finally my Impl class:
@Component
public class ValidCategoryImpl implements ConstraintValidator<ValidCategory, MenuCategory> {
@Autowired
IMenuCategoriesService menuCategoriesService;
@Override
public void initialize(ValidCategory constraintAnnotation){
}
@Override
public boolean isValid(MenuCategory menuCategory, ConstraintValidatorContext context){
return menuCategoriesService.containsCategoryName(menuCategory.getTitle());
}
}
Please help! I've been stuck for this and can't fix it! When i pass in the menuCategory it doesn't even go into the validation method? please help!
..Can't add a commment, but to answer the why question, this is what i think:
Similar to how @NotNull or @Size is invoked, I created my custom class, where my implementation is this - ConstraintValidator, so when MenuCategory is there it should go into this implementation method since I have @ValidCategory set-up to do so. What's your opinion? How do I make sure that validation happens?