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

标签 java spring bean-validation

我有两个类

@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/

相关文章:

spring - 通过 @RequestMapping 名称构建的 URL 无法按自定义名称的预期工作

java - CodeModel 如何添加@Pattern.List 注释 com.sun.codemodel

java - 如果JSON属性为空字符串,如何在Spring中配置JSON反序列化以设置空值?

java - 如何在java代码中获取unc路径的空闲空间?

java - Spring 的 Autowiring 、新操作符和困惑

spring - Intellij IDEA 是否支持@RooJpaRepository?

java - JSR-303/Spring MVC - 使用组进行条件验证

java - Pojo 验证有效。 Poko(kotlin)没有。为什么?

java - Java 中的继承和构造函数

java - 为什么命令行找不到我的 .java 文件?