gpt4 book ai didi

java - Spring 验证 JSR-303 @NotNull 抛出 NotReadablePropertyException

转载 作者:太空宇宙 更新时间:2023-11-04 10:20:33 25 4
gpt4 key购买 nike

我有两个类

@Data
@NoArgsConstructor
public class SearchProductOffer {
@Valid
private List<MatchProperty> properties = new ArrayList<>();
}
@Data
@NoArgsConstructor
public class MatchProperty {
private String version;
private String sourceSystem;
@NotNull(message = "Версия должна быть заполнена!")
public String codeName;
}

当我使用 ValidationUtil.invokeValidator 验证 A 时,我得到

2018-07-06 16:04:09.769 ERROR 10223 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.IllegalStateException: JSR-303 validated property 'properties[1].codeName' does not have a corresponding accessor for Spring data binding - check your DataBinder's configuration (bean property versus direct field access)] with root cause

org.springframework.beans.NotReadablePropertyException: Invalid property 'properties[1]' of bean class [java.lang.String]: Bean property 'properties[1]' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter? at org.springframework.beans.AbstractNestablePropertyAccessor.getPropertyValue(AbstractNestablePropertyAccessor.java:622) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]

当 fieldB 为空时。两个类都有 getter/setter。Spring Boot 2.0.3.RELEASE

更新每次我都会遇到异常,而我想在内部类中使用@NotNull(当字段值为空时)或@NotEmpty(当我的字段为“”)字段进行验证。

最佳答案

解决方案:删除 spring SmartValidator。在 Controller 中配置binder

@InitBinder
private void initBinder(WebDataBinder dataBinder) {
dataBinder.initDirectFieldAccess();
}

在启动配置中配置 validator

@Bean
public LocalValidatorFactoryBean getValidator() {
return new LocalValidatorFactoryBean();
}

并将其注入(inject) Controller

@Autowired
private LocalValidatorFactoryBean validator;

之后我们可以调用

List<ConstraintViolation<Object>> validationResult = new ArrayList<>();
validationResult.addAll(validator.validate(request));
validationResult.addAll(validator.validate(methodBean));

并检查validationResult是否有验证错误

关于java - Spring 验证 JSR-303 @NotNull 抛出 NotReadablePropertyException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51210771/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com