【问题标题】:Issue with using custom JSR303 annotation to validate method parameter in Spring mvc container使用自定义 JSR303 注释验证 Spring mvc 容器中的方法参数的问题
【发布时间】:2011-05-17 02:31:27
【问题描述】:

我使用 Spring 构建了一个简单的应用程序,并尝试实现自定义 JSR303 注释来验证方法字符串参数。我使用 Java 代码来配置 Spring 容器,并且我认为我已经加载了我需要的所有 Spring bean。但是验证注解还是不行。

代码如下:

配置 Spring:

@Configuration

@Lazy(false)

public class MVCContainerConfig 
{
    @Bean
    public AnnotationMethodHandlerAdapter annotationMethodHandlerAdapter()
    {
        ConfigurableWebBindingInitializer configurableWebBindingInitializer = new ConfigurableWebBindingInitializer();
        configurableWebBindingInitializer.setValidator(localValidatorFactoryBean());

        AnnotationMethodHandlerAdapter annotationMethodHandlerAdapter = new AnnotationMethodHandlerAdapter();
        annotationMethodHandlerAdapter.setWebBindingInitializer(configurableWebBindingInitializer);
        annotationMethodHandlerAdapter.setMessageConverters(new HttpMessageConverter[]{
            new BufferedImageHttpMessageConverter(), 
            new ByteArrayHttpMessageConverter(),
            new FormHttpMessageConverter(), 
            new ResourceHttpMessageConverter(), 
            new StringHttpMessageConverter(),
            new AtomFeedHttpMessageConverter(),
            new RssChannelHttpMessageConverter(),
            new MappingJacksonHttpMessageConverter(),
            new Jaxb2RootElementHttpMessageConverter(), 
            new MarshallingHttpMessageConverter(),
            new XmlAwareFormHttpMessageConverter()
        });

        return annotationMethodHandlerAdapter;
    }

    @Bean
    public DefaultAnnotationHandlerMapping defaultAnnotationHandlerMapping()
    {
        DefaultAnnotationHandlerMapping defaultAnnotationHandlerMapping = new DefaultAnnotationHandlerMapping();
        defaultAnnotationHandlerMapping.setInterceptors(new Object[]{localeChangeInterceptor(),
                                                                     themeChangeInterceptor()});
        return defaultAnnotationHandlerMapping;
    }

    @Bean(name="validator")
    public LocalValidatorFactoryBean localValidatorFactoryBean()
    {
        LocalValidatorFactoryBean localValidatorFactoryBean = new LocalValidatorFactoryBean();

        return localValidatorFactoryBean;
    }
... (ignore useless code)
}

注解定义:

@Documented
@Constraint(validatedBy={NotEmptyOrWhitespaceValidatorImp.class})
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@ReportAsSingleViolation
@NotNull
public @interface NotEmptyOrWhitespace 
{
    //TODO change this when language package is ready
    public abstract String message() default "Empty or white space error message";

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

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

    /**
     * Defines several {@code @NotEmptyOrWhitespace} annotations on the same element.
     */
    @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
    @Retention(RUNTIME)
    @Documented
    public @interface List {
        NotEmptyOrWhitespace[] value();
    }
}

约束定义:

public class NotEmptyOrWhitespaceValidatorImp implements ConstraintValidator<NotEmptyOrWhitespace, String>
{
    public void initialize(NotEmptyOrWhitespace annotation){}

    public boolean isValid(String str, ConstraintValidatorContext constraintValidatorContext) 
    {
        str = str.replaceAll(" ", "");
        return ((str == null || str.isEmpty()) ? false : true);
    }
}

我要测试的方法:

public boolean isOurProduct(@NotEmptyOrWhitespace String productName) 
    {
        productName = productName.trim().toLowerCase();
        return this.productSet.contains(productName);
    }

Junit 测试方法:

  @Test
        public void testIsOurProduct()
        {
            // If the annotation works, then I should see an exception occurred instead of the output
            System.out.println("********* "+this.finder.isOurProduct("  "));
        }

【问题讨论】:

  • 您的 MVCContainerConfig 类甚至无法编译。请给我们编译的示例代码。

标签: spring configuration spring-mvc annotations bean-validation


【解决方案1】:

请参阅Method Parameter Validation with JSR-303。您需要在方法调用上使用 AOP 触发验证。

【讨论】:

    猜你喜欢
    • 2013-07-13
    • 1970-01-01
    • 1970-01-01
    • 2014-09-24
    • 2011-07-08
    • 2013-05-18
    • 2016-09-26
    • 1970-01-01
    • 2011-09-21
    相关资源
    最近更新 更多