0

스프링을 사용하여 간단한 애플리케이션을 빌드하고 메소드 문자열 파라미터의 유효성을 검사하기 위해 사용자 정의 JSR303 어노테이션을 구현하려고합니다. Java 코드를 사용하여 Spring 컨테이너를 구성하고 필요한 모든 스프링 빈을로드했다고 생각합니다. 그러나 유효성 검사 주석은 여전히 ​​작동하지 않습니다.커스텀 JSR303 어노테이션을 사용하여 Spring MVC 컨테이너의 메소드 매개 변수를 유효화하는 문제

구성 봄 :

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

제약 정의 :

다음

코드입니다3210
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(" ")); 
     } 
+0

'MVCContainerConfig' 클래스는 컴파일되지 않습니다. 컴파일하는 예제 코드를 제공해주세요. – skaffman

답변

관련 문제