使用 bean 验证生成默认约束消息模板

Generating default constraint message template with bean validation

如果注释本身尚未定义此类消息模板,我将如何为约束(在 JPA 实体中)生成默认消息模板。

这就是我的意思。假设我有一个 JPA 实体 'Dummy':

@Entity
public class Dummy {
    @Column
    @NotNull
    Long id;
}

此外,假设我有一个 ValidationMessages.properties 文件包含:

Dummy.id.NotNull=ID of dummy should not be null

现在,如果我将 @NotNull 约束定义为 @NotNull(message={Dummy.id.NotNull}) 一切都会很好,但是如果我想生成 '{Dummy.id.NotNull} ' 动态模板(使用反射)所以我不必在每个约束上编写相同的标准化模板?我尝试使用 MessageInterpolator class,但是插值方法仅在定义消息属性时被调用,这违背了我想要做的事情的目的。

所以,为了让我自己清楚,我如何让验证器询问我的代码块"hey, what's the message for the constraint 'NotNull' on the field 'id' in the class 'Dummy' even though it has no message assigned (or rather, it has the default message assigned)?"

我错了 - 即使没有在注释上定义明确的消息,也会调用 MessageInterpolator。这几乎回答了我的问题。唯一剩下的就是弄清楚如何获取正在验证的字段名称。

编辑:

最后,我被迫为每个在构造函数中传递字段名称的字段实现一个 MessageInterpolator class,并在验证字段时使用该 MessageInterpolator 创建一个验证器。我觉得这并不令人满意,但这是我能想到的唯一解决方案。

在这个注释上,我觉得有趣的是,在访问注释 时无法追溯注释元素(无论是字段、方法、Class 还是参数)实例。如果这可能的话,我将能够动态获取字段名称,但这似乎是 Java 的 "lack",所以什么也做不了。