7

我有一个像这样的简单课程,

import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.Length;

public class Form implements Serializable {
   @NotNull
   @Length(min = 2, max = 20)
   private String lastName;
}

我在类路径中有 messages.properties 文件。然后通过 Spring bean 加载如下,

<bean name="validator"
      class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
    <property name="validationMessageSource">
        <ref bean="resourceBundleLocator"/>
    </property>
</bean>

<bean name="resourceBundleLocator" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="basenames">
        <list>
            <value>classpath*:messages.properties</value>
        </list>
    </property>
</bean>

我想要的只是根据经过验证的 bean 获得自定义的错误消息。换句话说,我想让每个 ConstraintViolation 对象返回我在属性文件中定义的错误消息,而不是默认的。是否可以添加具有这种格式 {xxx.yyyy.zzzz} 的值的消息属性并从 messages.properties 文件中引用该消息?

ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    Set<ConstraintViolation<Form>> inputErrors = validator.validate(form); 

如果我想自定义 @NotNull 和 @Length 的默认消息,我该怎么做?

我在 Hibernate 验证方面的经验为零,任何示例代码或分步指南 将不胜感激。

4

1 回答 1

4

您拥有保存消息值的资源包文件。

我认为您必须使用 ie@NotNull注释的路径来手动覆盖消息!喜欢javax.validation.constraints.NotNull=Notnull error happened! 或类似的东西!

在这里寻找:

Hibernate Validator - 错误信息

希望有帮助

于 2011-08-17T13:24:02.903 回答