如何获取Spring-Data-MongoDB来验证我的对象? [英] How to I get Spring-Data-MongoDB to validate my objects?

查看:105
本文介绍了如何获取Spring-Data-MongoDB来验证我的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的使用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);
    }
}

我看到某个地方只有在上下文中创建了验证器的情况下才会启动验证,因此我尝试更新Application类(其中包含所有配置,看起来像这样

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

}

推荐答案

首先请确保您在类路径上具有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();
}

Voilà!验证现已开始.

Voilà! Validation is working now.

这篇关于如何获取Spring-Data-MongoDB来验证我的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆