You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Spring消息插值中使用同一类的其他对象字段值

需求可行性说明

这个需求是可行的,Bean Validation(比如常用的Hibernate Validator)支持在约束消息中通过EL表达式引用当前对象的其他字段值,只需调整代码中的语法问题并遵循规范即可实现。

修正后的示例代码

实体类定义

public class Car {
    @NotEmpty(message = "The car of the model '${model}' requires a plate_number")
    private String plateNumber;

    private String model;

    // 建议添加getter方法,确保验证器能正确访问model字段
    public String getModel() {
        return model;
    }

    // 构造方法
    public Car(String plateNumber, String model) {
        this.plateNumber = plateNumber;
        this.model = model;
    }
}

实例创建与验证

// 正确创建实例(字符串需加引号)
Car myCar = new Car(null, "Audi");

// 执行验证逻辑(示例简化)
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<Car>> violations = validator.validate(myCar);

// 输出验证消息
for (ConstraintViolation<Car> violation : violations) {
    System.out.println(violation.getMessage());
}

执行后会输出期望的消息:The car of the model 'Audi' requires a plate_number

关键注意事项

  • 消息中的EL表达式无需加this.,直接使用字段名即可;若字段为private,建议添加对应getter方法,部分验证器实现依赖getter获取属性值
  • 确保使用的Bean Validation实现版本支持EL表达式,主流的Hibernate Validator 5.x及以上版本均支持该特性
  • 原示例代码存在语法错误:类定义需加class关键字、字符串常量需加双引号、实例创建时字符串参数需加引号,这些都需要修正才能正常编译运行

内容的提问来源于stack exchange,提问作者Jjimenez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 23:37:06