如何在 ConstraintValidator 中自动装配服务

Muf*_*anu 5 java spring-mvc bean-validation

我正在使用 Spring MVC 编写我的应用程序。我想验证用户注册时数据库中是否存在电子邮件。我已经编写了自己的名为UniqueEmail的注释约束。

我的用户实体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;
}
Run Code Online (Sandbox Code Playgroud)

我的注释约束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 {};
}
Run Code Online (Sandbox Code Playgroud)

我的验证器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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

此代码适用于应用程序。

当我运行我的测试代码时,它返回 NullPointerException。在我的验证类userService 中为 null。

我已经阅读了http://docs.spring.io/spring/docs/3.0.0.RC3/reference/html/ch05s07.html但没有任何解决方案。

任何的想法?

更新

我使用 JUnit。用户类测试.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("mail@example.com"); // 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());
    }
}
Run Code Online (Sandbox Code Playgroud)

更新

<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/>
Run Code Online (Sandbox Code Playgroud)

Sol*_*ris 0

如果您的主代码可以正常工作,那么您的测试应该可以直接工作。您需要在测试类上使用@ContextConfiguration,有关更多详细信息,请参阅此: http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/testing.html

一般来说,有两种方法可以测试:

  • 单元测试
  • 集成测试

对于单元测试,您需要创建 UniqueEmailValidator 的实例并在该实例上设置 UserService(通常是模拟 UserServer)。

对于集成测试,您需要像我上面提到的那样初始化 spring 上下文。