2014-01-24 2 views
1

Spring MVC를 사용하여 응용 프로그램을 작성하고 있습니다. 사용자가 등록 할 때 데이터베이스에 전자 메일이 있는지 확인하려고합니다. 나는 UniqueEmail이라는 내 자신의 주석 제한을 작성했습니다.ConstraintValidator에서 서비스를 autowire하는 방법

내 사용자 개체 User.java :

@Entity 
@Table(name="users") 
public class User { 

    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    private Integer id; 

    @Column(name = "email", length = 100, nullable = false, unique = true) 
    @NotEmpty 
    @Email 
    @UniqueEmail(message = "E-mail is not unique") 
    private String email; 

    @Column(name = "password", nullable = false) 
    @NotEmpty 
    @Size(min = 5, message = "size must be more 5") 
    private String password; 
} 

내 주석 제약 UniqueEmail.java :

@Target({FIELD}) 
@Retention(RUNTIME) 
@Constraint(validatedBy = UniqueEmailValidator.class) 
@Documented 
public @interface UniqueEmail { 
    String message() default "Email is exist"; 

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

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

내 검증 UniqueEmailValidator.java :

@Component 
public class UniqueEmailValidator implements ConstraintValidator<UniqueEmail, String> { 

    @Autowired 
    private UserService userService; 

    @Override 
    public void initialize(UniqueEmail uniqueEmail) { 
    } 

    @Override 
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) { 
     try { 
      return userService.isExistEmail(s); 
     } catch (Exception e) { 
      System.out.println(e); 
      return false; 
     } 
    } 
} 
,536,

이 코드는 응용 프로그램에서 작동합니다.

테스트 코드를 실행하면 해당 NullPointerException이 반환됩니다. 유효성 검사 클래스에서 userService이 null입니다.

나는 http://docs.spring.io/spring/docs/3.0.0.RC3/reference/html/ch05s07.html을 읽었지만 어떤 해결책도 없습니다.

아이디어가 있으십니까?

업데이트 내가 JUnit을 사용합니다. UserClassTest.java

@ContextConfiguration("file:src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml") 
public class UserClass { 

    private static Validator validator; 

    @BeforeClass 
    public static void setup() { 
     ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); 
     validator = factory.getValidator(); 
    } 

    @Test 
    public void emailIsUnique() { 

     User user = new User(); 
     user.setEmail("[email protected]"); // I've written exist email in DB. 

     Set<ConstraintViolation<User>> constraintViolations = validator.validateProperty(user, "email"); 

     assertEquals(1, constraintViolations.size()); 
     assertEquals("E-mail is not unique", constraintViolations.iterator().next().getMessage()); 
    } 
} 

업데이트

<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:context="http://www.springframework.org/schema/context" 
    xmlns:mvc="http://www.springframework.org/schema/mvc" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd 
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> 

<context:component-scan base-package="ru.yadoka"/> 

<import resource="db/db-config.xml"/> 

<!-- Apache tiles --> 
<bean id="tilesConfigurer" 
     class="org.springframework.web.servlet.view.tiles3.TilesConfigurer"> 
    <property name="definitions"> 
     <list> 
      <value>/WEB-INF/tiles.xml</value> 
     </list> 
    </property> 
</bean> 

<bean id="viewResolver" 
     class="org.springframework.web.servlet.view.UrlBasedViewResolver"> 
    <property name="viewClass" value="org.springframework.web.servlet.view.tiles3.TilesView"/> 
</bean> 

<!-- Mapping resources from theme --> 
<mvc:resources mapping="/css/**" location="/resources/css/"/> 
<mvc:resources mapping="/js/**" location="/resources/js/"/> 
<mvc:resources mapping="/fonts/**" location="/resources/ 
<mvc:annotation-driven/> 

+0

, 당신이 제대로 autowire가 필요가 없습니다. – Eugene

+0

applicationcontext에서 을 사용하고 있습니까? – Koitoer

+0

Kiotoer - 예''. 내 컨트롤러에서 userService가 올바르게 자동으로 실행됩니다. – Mufanu

답변

0

주요 코드가 작동하면, 다음은 테스트 작업을 얻기 위해 정직해야한다. 당신은 당신의 테스트 클래스에 @ContextConfiguration를 사용해야 자세한 내용은이를 참조하십시오

단위 테스트의 경우 UniqueEmailValidator의 인스턴스를 만들고 해당 인스턴스 (일반적으로 모의 UserServer)에 UserService를 설정해야합니다.

통합 테스트의 경우 위에서 언급 한 스프링 컨텍스트를 초기화해야합니다.

+0

내 게시물을 업데이트했습니다. UniqueEmailValidotor의 인스턴스를 만들고 UserService를 설정하는 방법은 무엇입니까? – Mufanu

+0

당신은 mvc-dispatcher-servlet.xml을 게시 할 수 있습니까 – Solubris

+0

게시하려면 config를 추가했습니다. – Mufanu

1

빈 컨텍스트에서 유효성 검사기를 구성하지 않았습니까? 부트 스트랩하는 경우 Validator via Validation.buildDefaultValidatorFactory(); 당신은 Spring 메커니즘을 우회하고 Spring Bean과 컴포넌트를 인식하지 못하는 Validator를 얻습니다. 따라서 주사가 작동하지 않습니다. 테스트에서 제공하는 Validator를 보유하고 싶습니다.

0

당신은 주입 모든 @Autowired 서비스를 호출 할 수 userService가 null의 경우

@Override 
public void initialize(UniqueEmail uniqueEmail) { 
    org.springframework.web.context.support.SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this); 
} 
관련 문제