通过检查字典进行Spring验证 [英] Spring validation with checking a dictionary

查看:91
本文介绍了通过检查字典进行Spring验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Spring RestController和hibernate验证器。

需要创建一些验证注释,用于检查某些字典(预设数组或某些数据库)中的验证字段。



例如,我有一些bean

  @Service 
public class MyDict {

public boolean containsWord(String word){
...
}
}



以及一些数据,我检查了

  public class ResponseData {

@IsInDictionary(MyDict.class)
私有字符串字;


当我直接调用hibernate验证,或者使用 @Valid 注解在RequestMapping方法中,我想让validator调用MyDict的bean方法containsWord(word)。

有没有人有您需要定义您自己的注释,然后定义您自己的 Validator

解决方案 $ c>您将在哪里执行验证逻辑(在本例中为字典查找)

您可以在这里阅读更多信息: https://docs.jboss.org /hibernate/validator/4.1/reference/en-US/html/validator-customconstraints.html#validator-customconstraints-constraintannotation



创建自己的注释,你只需扩展 ConstraintValidator< YourCustomAn notation,String> ,你已经准备好了。方法 isValid()需要在您提到的逻辑内执行: containsWord(word)



好的一点是,您的自定义验证器可以是Spring管理的bean,因此您可以自由地向其中注入内容,例如执行数据库查找。因此,在这种情况下,您需要注入字典并在那里执行检查。


Using Spring RestControllers with hibernate validator.

Need to create some Validation annotation, that check the validating field presents in some dictionary (preset array or some DB).

For example, I have some bean

@Service
public class MyDict {

   public boolean containsWord(String word) {
       ...
   }
} 

And some data, I check

public class ResponseData {

    @IsInDictionary(MyDict.class)
    private String word;

}

And when I call hibernate validation directly, or with @Valid annotation in RequestMapping method, I want validator to call MyDict bean method containsWord(word).

Does anybody have any ideas?

解决方案

You need to define your own annotation and then define your own Validator where you will be performing your validation logic (in this case, a dictionary lookup)

You can read more about this here: https://docs.jboss.org/hibernate/validator/4.1/reference/en-US/html/validator-customconstraints.html#validator-customconstraints-constraintannotation

After creating your own annotation, you just extend ConstraintValidator<YourCustomAnnotation, String> and you are pretty much ready to go. Method isValid() needs to perform inside the logic you mentioned: containsWord(word)

The nice thing is that your custom validator can be a Spring-managed bean so you can freely inject stuff into it and for example, perform a DB lookup. So in this case, you would need to inject your dictionaries and perform a check there.

这篇关于通过检查字典进行Spring验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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