基于注释的Spring bean验证 [英] annotation based Spring bean validation

查看:130
本文介绍了基于注释的Spring bean验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究使用弹簧模块验证Spring bean的基于注释的方法。在本教程中,以下bean(省略了getter和setter)是用作示例:

I'm investigating an annotation-based approach to validating Spring beans using spring modules. In this tutorial, the following bean (getters and setters omitted) is used as an example:

public final class User {  

  @NotBlank  
  @Length(max = 80)  
  private String name;  

  @NotBlank  
  @Email  
  @Length(max = 80)  
  private String email;  

  @NotBlank  
  @Length(max = 4000)  
  private String text;  
}

如果违反特定验证规则,则使用的错误消息应遵循此格式:

The error message that is used if a particular validation rule is disobeyed should follow this format:

bean-class.bean-propery[validation-rule]=Validation Error message

上面显示的类的示例包括:

Examples for the class shown above include:

User.email[not.blank]=Please enter your e-mail address.  
User.email[email]=Please enter a valid e-mail address.  
User.email[length]=Please enter no more than {2} characters.

消息键包含类名这一事实带来了一些问题:

The fact that the message keys contain the class name presents a couple of problems:


  1. 如果重命名了类,则还需要更改消息键

  2. 如果我有另一个类(例如Person),其电子邮件属性与User.email完全相同,我需要复制邮件,例如

  1. If the class is renamed, the message keys also need to be changed
  2. If I have another class (e.g. Person) with an email property that is validated identically to User.email, I need to duplicate the messages, e.g.

Person.email [not.blank] =请输入您的电子邮件地址。

Person.email [email] =请输入有效的电子邮件地址。

Person.email [length] =请输入不超过{ 2}字符。

Person.email[not.blank]=Please enter your e-mail address.
Person.email[email]=Please enter a valid e-mail address.
Person.email[length]=Please enter no more than {2} characters.

事实上,文档声称可以为特定规则配置默认消息(例如@Email)像这样:

In fact, the documentation claims that is possible to configure a default message for a particular rule (e.g. @Email) like this:

email=email address is invalid

如果找不到规则的特定于bean的消息,则应使用此默认消息。但是,我的经验是,这根本不起作用。

This default message should be used if a bean-specific message for the rule cannot be found. However, my experience is that this simply does not work.

避免重复消息的另一种机制是将错误消息的密钥传递给规则注释。例如,假设我为@Email规则定义了以下默认错误消息

An alternative mechanism for avoiding duplicate messages is to pass the key of the error message to the rule annotation. For example, assume I have defined the following default error message for the @Email rule

badEmail=Email address is invalid

如果我注释相关属性,则应使用此消息:

This message should be used if I annotate the relevant property like this:

@Email(errorCode="badEmail")
private String email;

然而,我一次又一次地试了这个,它似乎不起作用。有没有人找到一种方法来避免在使用此验证框架时重复错误消息?

However I tried this, out and again, it just doesn't seem to work. Has anyone found a way to avoid duplicating error messages when using this validation framework?

推荐答案

我快速浏览了 BeanValidator API ,看起来您可能想要尝试 errorCodeConverter 属性。

I took a quick look at the BeanValidator API, and it looks like you might want to try the errorCodeConverter property.

您需要实现你自己的 ErrorCodeConverter ,还是使用其中一个提供的实现?

You would need to implement your own ErrorCodeConverter, or use one of the provided implementations?

....
<bean id="validator" class="org.springmodules.validation.bean.BeanValidator"
    p:configurationLoader-ref="configurationLoader"
    p:errorCodeConverter-ref="errorCodeConverter" />

<bean id="errorCodeConverter" class="contact.MyErrorCodeConverter" />
....

注意:configurationLoader是配置中定义的另一个bean本教程中使用的XML

示例转换器:

package contact;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springmodules.validation.bean.converter.ErrorCodeConverter;

public class MyErrorCodeConverter implements ErrorCodeConverter {

    private Log log = LogFactory.getLog(MyErrorCodeConverter.class);

    @Override
    public String convertPropertyErrorCode(String errorCode, Class clazz, String property) {
        log.error(String.format("Property %s %s %s", errorCode, clazz.getClass().getName(), property));
        return errorCode;  // <------ use the errorCode only
    }

    @Override
    public String convertGlobalErrorCode(String errorCode, Class clazz) {
        log.error(String.format("Global %s %s", errorCode, clazz.getClass().getName()));
        return errorCode;
    }
}

现在属性应该有效:

MyEmailErrorCode=Bad email

class Foo {
    @Email(errorCode="MyEmailErrorCode")
    String email
}

这篇关于基于注释的Spring bean验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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