gpt4 book ai didi

java - 如何在 ConstraintValidator 中 Autowiring 服务

转载 作者:搜寻专家 更新时间:2023-11-01 03:38:37 25 4
gpt4 key购买 nike

我正在使用 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;
}

我的注解约束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 {};
}

我的 validator 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;
}
}
}

此代码在应用程序中有效。

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

我读过 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("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());
}
}

更新

<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/>

最佳答案

您的 bean 上下文中没有配置 validator 吗?如果您通过 Validation.buildDefaultValidatorFactory(); 引导 Validator,您将绕过 Spring 机制,并且您会得到一个不知道 Spring bean 和组件的 Validator。因此注入(inject)不起作用。在您的测试中,您希望获得 Spring 提供的 validator 。

关于java - 如何在 ConstraintValidator 中 Autowiring 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21338883/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com