如何让 Spring-Data-MongoDB 验证我的对象? [英] How to I get Spring-Data-MongoDB to validate my objects?
问题描述
我有一个使用 Spring-Data-Mongodb 的非常简单的 Spring Boot 应用程序
I have a very simple Spring Boot application that uses Spring-Data-Mongodb
我想要做的就是设置一个 JSR-303 验证规则,说明我要保存的对象必须有一个用户名.我读到 JSR-303 在 1.1 版中被添加到 spring-data-mongodb 中,所以我假设当我保存一个对象时,它已经过验证,但事实并非如此.
All I want to do is set a JSR-303 validation rule that says the object I'm saving must have a username. I read that JSR-303 was added to spring-data-mongodb in version 1.1 so I assumed that when I save an object it's validated but this isn't the case.
有没有人有一个简单的示例设置来展示它是如何工作的?
Does anyone have a simple example setup that shows how this works?
我的用户 pojo 看起来像
My User pojo looks like
public class User {
@Id
private String id;
@NotNull(message = "User Name is compulsory")
private String userName;
private String password;
public User() {}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = PasswordAuthService.hash(password);
}
}
我看到某处只有在上下文中创建了验证器时才会进行验证,因此我尝试更新我的应用程序类(其中包含所有配置,看起来像
I saw somewhere that validation only kicks in if you have a validator created in the context so I tried updating my Application class (which contains all the configuration, to look like
@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application {
@Bean
public Validator getValidator() {
LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
return validator;
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
推荐答案
首先确保你在 classpath 上有 JSR-303 验证器,例如:
First make sure that you have JSR-303 validator on classpath, for example:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.2.0.Final</version>
</dependency>
如果你使用 Java 配置,那么要走的路是创建 2 个 bean:
If you use Java config, the way to go is to create 2 beans:
@Bean
public ValidatingMongoEventListener validatingMongoEventListener() {
return new ValidatingMongoEventListener(validator());
}
@Bean
public LocalValidatorFactoryBean validator() {
return new LocalValidatorFactoryBean();
}
瞧!验证正在进行中.
这篇关于如何让 Spring-Data-MongoDB 验证我的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!