Spring MVC验证不起作用(注释)

时间:2014-06-23 02:28:57

标签: java spring validation spring-mvc

我尝试使用注释验证,但它无法正常工作。 这是我的服务界面,我正在应用验证:

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

这是我的验证课程

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

最后我的Impl课程:

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

请帮忙!我已经被困住了,无法修复它! 当我通过menuCategory时,它甚至没有进入验证方法?请帮忙!

..无法添加通知,但为了回答原因,我认为这是:

类似于调用@NotNull或@Size的方式,我创建了我的自定义类,我的实现是这样的 - ConstraintValidator,所以当MenuCategory存在时,它应该进入这个实现方法,因为我有@ValidCategory设置要做所以。你的意见是什么?如何确保验证发生?

0 个答案:

没有答案