Spring Boot 中的 DTO 验证不起作用
我有一个带有 POST 方法的控制器:
@RestController
@RequestMapping(value = "/creditDetails", produces = MediaType.APPLICATION_JSON_VALUE)
@RequiredArgsConstructor
@Validated
public class CreditDetailsController {
@ResponseStatus(HttpStatus.CREATED)
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
public CreditDetailsResponse createCreditDetails(@RequestBody @Valid CreditDetailsRequestWithoutId request) {
return CreditDetailsResponse.convertToResponse(creditDetailsService.createCreditDetails(request));
}
}
和 DTO:
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class CreditDetailsRequestWithoutId {
@DecimalMax("10_000_000")
private BigDecimal creditLimit;
@DecimalMin("0")
@DecimalMax("20")
private BigDecimal creditPercent;
private UUID bankId;
}
当我以 111% 传递 CreditDetailsWithoutId 实例时,我没有收到任何错误。为什么我的验证不起作用? 如果重要的话我使用
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
<version>2.6.3</version>
</dependency>
I have a controller with POST method:
@RestController
@RequestMapping(value = "/creditDetails", produces = MediaType.APPLICATION_JSON_VALUE)
@RequiredArgsConstructor
@Validated
public class CreditDetailsController {
@ResponseStatus(HttpStatus.CREATED)
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
public CreditDetailsResponse createCreditDetails(@RequestBody @Valid CreditDetailsRequestWithoutId request) {
return CreditDetailsResponse.convertToResponse(creditDetailsService.createCreditDetails(request));
}
}
And DTO:
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class CreditDetailsRequestWithoutId {
@DecimalMax("10_000_000")
private BigDecimal creditLimit;
@DecimalMin("0")
@DecimalMax("20")
private BigDecimal creditPercent;
private UUID bankId;
}
When I pass the CreditDetailsWithoutId instance with 111 percent I don't get any errors. Why my validation didn't work?
If it matter i use
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
<version>2.6.3</version>
</dependency>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试将十进制值传递给@DecimalMin、@DecimalMax:
@DecimalMax:字段或属性的值必须是小于或等于值元素中的数字的十进制值。 参考
稍后编辑: 删除 @Data 并添加基本吸气剂和设置者解决了我这边的问题,希望它有效。
Try to pass a decimal value to @DecimalMin, @DecimalMax,:
@DecimalMax: The value of the field or property must be a decimal value lower than or equal to the number in the value element. reference
Later edit: Removing @Data and adding basic getters & setters fixed the problem on my side, hope it works.
我刚刚调用了
maven clean install
并开始了验证I've just called
maven clean install
and validation started对于我的工作:
pom.xml:
控制器:
Dto:
完全@Validated
for my work this:
pom.xml:
Controller:
Dto:
exactly @Validated
您必须在控制器类中添加 EExceptionHandler:
You must add EexceptionHandler in your controller class: