这对我来说很奇怪。我之前已经完成了实体、控制器和表单验证,但我对这个错误感到困惑。
所以背景故事。这是带休眠的 spring-boot,连接到 PostgreSQL 数据库。我正在尝试做的是将 POST 请求映射到创建资源。我正在尝试使用纯 JSON 来做到这一点。我以前已经能够做到这一点。
有问题的错误是...
Bean 类 [com.example.api.entities.forms.OrganizationRegistrationForm] 的属性"Test"无效:Bean 属性 'Test' 不可读或具有无效的 getter 方法: getter 的返回类型是否与 setter 的参数类型匹配?
请求正文,就像它在邮递员中一样是...
{
"organizationName":"Test",
"employees":10
}
它抱怨的组织注册表单类...
public class OrganizationRegistrationForm {
@NotEmpty
private String organizationName = "";
@NotNull
private int employees;
private JsonNode contactInfo;
private JsonNode locationInfo;
public String getOrganizationName() {
return organizationName;
}
public void setOrganizationName(String name) {
this.organizationName = name;
}
public int getEmployees() {
return employees;
}
public void setEmployees(int employees) {
this.employees = employees;
}
public JsonNode getContactInfo() {
return contactInfo;
}
public void setContactInfo(JsonNode contactInfo) {
this.contactInfo = contactInfo;
}
public JsonNode getLocationInfo() {
return locationInfo;
}
public void setLocationInfo(JsonNode locationInfo) {
this.locationInfo = locationInfo;
}
}
如果您需要它,请求方法...
@RequestMapping(value="/organization", method = RequestMethod.POST)
public Organization registerOrganization(@Valid @RequestBody OrganizationRegistrationForm form,
BindingResult bindingResult) throws Exception {
if(bindingResult.hasErrors()) {
LOGGER.error("The registration form entered has errors: {}", bindingResult.getAllErrors().toString());
throw new InvalidForm();
}
try {
Organization org = orgService.registerOrganization(form);
if(org!=null)
return org;
} catch(DataIntegrityViolationException e) {
bindingResult.reject("name.exists", "The supplied name is already in use");
}
throw new InvalidForm();
}
虽然我猜它甚至没有走那么远。最初,orginazationName字段称为"name",但我对其进行了更改,以查看是否是问题所在。
对我来说更奇怪的部分是当我使用这个 JSON 对象时它起作用了。但创建了一个名为"组织名称"的组织。
{
"organizationName":"organizationName",
"employees":10
}
有一次它甚至抱怨无效属性是"。就像在空中一样。我在这里做错了什么?
怎么做,或者为什么。但出于某种原因,答案似乎在绑定程序使用的 OrganizationRegistrationFormValidator 类中。
有问题的邪恶行在验证(对象目标,错误错误)方法中...
ValidationUtils.rejectIfEmptyOrWhitespace(errors, target.getOrganizationName(), "name.empty", "Please enter a name");
将该行更改为经典检查有效。
if(target.getOrganizationName.isEmpty())
errors.reject("name.empty", "Please enter a name");
为了文档的缘故,有人知道为什么会这样吗?当智能感知建议该方法签名时,我的 api 文档是否错误?
这很旧,但我只是偶然发现了它:
对我来说,ValidationUtils.rejectIfEmptyOrWhitespace(errors, target.getOrganizationName(), "name.empty", "Please enter a name");
看起来不对劲。
它应该是:
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "organizationName", "name.empty", "Please enter a name");
第二个属性是字段名称,而不是其内容。ValidationUtils 将采用该名称并将其转换为标准 getter(在本例中为 getOrganizationName)以检索其值并对其进行验证。
这就是为什么它告诉你没有名为 Test 的属性。因为没有。