0

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

这是代码:

配置弹簧:

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

1 回答 1

0

请参阅JSR-303 的方法参数验证。您需要在方法调用上使用 AOP 触发验证。

于 2011-02-06T04:21:06.287 回答