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

Hibernate Validator消息插值时如何访问实例变量?

解决Hibernate Validator字段级约束消息访问Bean其他属性的问题

你可以通过消息表达式中的${root}变量直接访问当前被验证的Bean实例,无需使用类级约束。

具体实现步骤:

  1. 修改字段级约束的消息表达式
    在@NotBlank的消息中使用${root.id}来引用Person实例的id字段:

    public class Person {
        public int id;
    
        @NotBlank(message="User with id: ${root.id} is missing name")
        public String name;
    }
    

    这里的root代表当前正在被验证的Person对象,通过它可以访问Bean的任意公共字段;如果是私有字段,需要提供对应的getter方法,Hibernate Validator会自动通过getter获取属性值。

  2. 确保Spring Data JPA触发验证
    要让CrudRepository::save时自动触发验证,需要在Repository接口中做如下配置:

    import org.springframework.data.repository.CrudRepository;
    import org.springframework.validation.annotation.Validated;
    import javax.validation.Valid;
    
    @Validated
    public interface PersonRepository extends CrudRepository<Person, Integer> {
        @Override
        <S extends Person> S save(@Valid S entity);
    }
    
    • @Validated标注在Repository接口上,开启Spring的方法级验证支持
    • 在save方法的参数上添加@Valid,触发对传入实体的验证

这样当调用save方法时,如果name为空,验证失败的消息会正确显示对应的id值,完全不需要依赖类级约束。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 04:15:09