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

Java Play 2.6.x缓存清理方法及JSR-303数据绑定错误求助

解决JSR-303验证的Accessor缺失错误

你碰到的这个IllegalStateException,说白了就是Play的数据绑定器找不到ean字段对应的getter/setter,或者配置没开字段直接访问,下面几个方法一步步排查:

1. 先检查Getter/Setter有没有写对

Play默认按JavaBean规范做数据绑定,给ean加了验证注解(比如@NotEmpty、@Pattern),就得有对应的getEan()和setEan(),而且方法名要严格符合规范,大小写不能错:

import javax.validation.constraints.NotEmpty;

public class ProductForm {
    @NotEmpty(message = "EAN码不能为空")
    private String ean;

    // 必须要有getter
    public String getEan() {
        return ean;
    }

    // 接收前端数据的话,setter也不能少
    public void setEan(String ean) {
        this.ean = ean;
    }
}

2. 不想写Getter/Setter?直接开字段访问

如果嫌写get/set麻烦,可以配置DataBinder直接访问字段。在Play 2.6里,有两种方式:

  • 方式一:用Lombok的@Data注解,自动生成get/set,还支持字段访问,省事:
    import lombok.Data;
    import javax.validation.constraints.NotEmpty;
    
    @Data
    public class ProductForm {
        @NotEmpty(message = "EAN码不能为空")
        private String ean;
    }
    
  • 方式二:全局配置DataBinder允许字段访问,写个配置类就行:
    import play.data.FormFactory;
    import org.springframework.validation.DataBinder;
    import javax.inject.Inject;
    import javax.inject.Singleton;
    
    @Singleton
    public class DataBinderConfig {
        @Inject
        public DataBinderConfig(FormFactory formFactory) {
            DataBinder binder = formFactory.form().getBinder();
            // 开启直接字段访问
            binder.initDirectFieldAccess();
            // 允许所有字段绑定
            binder.setAllowedFields("*");
        }
    }
    

3. 检查注解里的字段名和实体类是否匹配

有时候可能是手滑,验证注解里写错了字段名,比如实体类是eanCode,但注解里写了ean,也会报这个错,仔细核对一下。

4. 前端表单参数名要和字段一致

如果是前端提交数据,要确保input的name属性和实体类字段名完全一样,比如<input type="text" name="ean" />,不然Play找不到对应的字段绑定。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:03:05