英文:
Spring boot javax validation annotations are not working
问题
我在spring-boot 3.1.0上有一个项目。我有一个包含验证注解字段的请求dto:
@Data
@Valid
public class RequestDto {
@NotNull
private String title;
@Positive
private Integer episodesCount;
...
}
我在Api接口上添加了Valid
和Validated
:
@Validated
public interface Api {
@PutMapping("/{id}")
@ResponseStatus(HttpStatus.OK)
void update(@PathVariable UUID id, @Valid @RequestBody RequestDto requestDto);
}
我在pom中添加了两个依赖项:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
但问题是它没有工作,它仍然接受-1
参数,而应该只接受正数。为什么不起作用?我尝试在实现Api接口的Controller本身上添加Validated
和Valid
,也没有帮助。
更新:我不能删除javax依赖,因为没有它就没有@NotNull
和@Positive
。还尝试删除除了方法参数之外的所有地方的@Valid
和@Validated
,但没有帮助。
更新:我的Controller实现:
@RestController
@RequiredArgsConstructor
public class Controller implements Api {
@Override
public void update(UUID id, RequestDto requestDto) {
...
}
}
英文:
I have a project on spring-boot 3.1.0. I have a request dto that contains fields with validation annotations:
@Data
@Valid
public class RequestDto {
@NotNull
private String title;
@Positive
private Integer episodesCount;
...
}
I've added Valid
and Validated
on Api interface:
@Validated
public interface Api {
@PutMapping("/{id}")
@ResponseStatus(HttpStatus.OK)
void update(@PathVariable UUID id, @Valid @RequestBody RequestDto requestDto);
I added two dependencies to the pom:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
But the problem that it's not working, it still takes -1
argument when it should take only positive ones. Why is that not working? I tried to put Validated
and Valid
on the Controller
itself that implements Api interfact, also didn't help.
UPD: I can't delete javax dependency since without it there are no @NotNull
and @Positive
. Also, tried to delete @Valid
and @Validated
everywhere except method parameter, didn't help.
UPD: My controller implementation:
@RestController
@RequiredArgsConstructor
public class Controller implements Api {
@Override
public void update(UUID id, RequestDto requestDto) {
...
}
}
答案1
得分: 1
删除javax
依赖项并将<artifactId>spring-boot-starter-validation</artifactId>
指定为3.1.0
版本有所帮助。
英文:
Deleting javax
dependency and specifying <artifactId>spring-boot-starter-validation</artifactId>
to 3.1.0
version helped.
答案2
得分: -2
移除 validation-api 依赖和 RequestDto 类上的 @Valid 注解,尝试刷新 Maven。这可能会有所帮助。
英文:
Remove validation-api dependency and @Valid annotation on the RequestDto class ,try refresh maven.This might help you.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论