ST-*_*DDT 7 java validation spring hibernate-validator maven
我有一个Spring-JSON/RestAPI,它使用注释驱动的输入验证. @Valid
当我尝试验证另一个对象内的对象时,我收到以下错误.
java.lang.IllegalStateException: JSR-303 validated property 'client.application' does not have a corresponding accessor for Spring data binding - check your DataBinder's configuration (bean property versus direct field access)
at org.springframework.validation.beanvalidation.SpringValidatorAdapter.processConstraintViolations(SpringValidatorAdapter.java:153) ~[spring-context-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.validation.beanvalidation.SpringValidatorAdapter.validate(SpringValidatorAdapter.java:108) ~[spring-context-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.validation.DataBinder.validate(DataBinder.java:866) ~[spring-context-4.3.2.RELEASE.jar:4.3.2.RELEASE]
...
Run Code Online (Sandbox Code Playgroud)
以下是此处使用的json数据模型:
{ // @Valid MessageDTO
"title": "Test",
"message":"Test",
"client": { // @Valid ClientDTO
"application": "Test"
}
}
Run Code Online (Sandbox Code Playgroud)
我在这里跳过了java定义,因为它会有太多无用的噪音IMO.
我不想/不能轻易地将getter或setter添加到我的DTO中,那么我该如何关注该错误消息并将我的DataBinder配置为使用"直接字段访问"?我想为此使用JavaConfig(@Configuration).
使用以下依赖项:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.4.Final</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
编辑:
控制器:
@RequestMapping(path = "/send", method = { RequestMethod.POST, RequestMethod.PUT })
public void send(@Valid @RequestBody MessageDTO message)
Run Code Online (Sandbox Code Playgroud)
MessageDTO:
public class MessageDTO {
...
@Valid
@NotNull
public ClientDTO client;
}
Run Code Online (Sandbox Code Playgroud)
ClientDTO:
public class ClientDTO {
...
@NotEmpty
public String application;
}
Run Code Online (Sandbox Code Playgroud)
小智 19
我偶然发现了同样的问题并为我们找到了解决方案,并且只想分享它.
在资源或@ControllerAdvice您可以配置Spring DataBinder以使用直接字段访问.
@ControllerAdvice
public class CustomControllerAdvice {
@InitBinder
private void activateDirectFieldAccess(DataBinder dataBinder) {
dataBinder.initDirectFieldAccess();
}
...
}
Run Code Online (Sandbox Code Playgroud)
对我来说,解决方案是在 DTO 中添加 getter 和 setter
public class MessageDTO {
...
@Valid
@NotNull
public ClientDTO client;
@NotNull public ClientDTO getClient() { return client; }
public void setClient(@NotNull ClientDTO client) { this.client = client; }
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3390 次 |
| 最近记录: |