I was recently trying to learn Spring and Java 17 as I only have experience with Dropwizard and Java 11, and I would like to do validation on a POJO, in a POST or PUT request.
I've encountered several examples, but locally testing, I don't seem to be able to actually run into the validation, at first I thought it might be a Records issue so I've fallen back to Class and I still cannot validate it, any clues as to what the issue might be?

我的控制器:

@RestController
public class HelloWorldController {

//... other GET APIs

  @PostMapping("/userProfile")
  @ResponseStatus(HttpStatus.CREATED)
  public ResponseEntity<UserProfileClass> addUserProfile(@RequestBody @Valid UserProfileClass userProfile) {
    System.out.println("Inserting in the database: " + userProfile);
    return ResponseEntity.ok(userProfile);
  }

POJO(UserProfileClass):

public class UserProfileClass {

    @NotNull @NotBlank String name;
    @NotBlank @NotNull String address;
    //... getters and setters

包含验证器的pom.xml:

    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
        <version>2.0.1.Final</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-validation</artifactId>
    </dependency>

如果我在本地运行它,并在IntelliJ上发布以下内容:

POST http://localhost:8080/userProfile
Content-Type: application/json

{
  "name": "some Name"
}

我总是得到200分,身体是这样的:

HTTP/1.1 200 
Content-Type: application/json
Transfer-Encoding: chunked
Date: Sun, 18 Feb 2024 23:21:46 GMT
Keep-Alive: timeout=60
Connection: keep-alive

{
  "name": "some Name",
  "address": null
}

正如@NotNull显然不应该让它通过的那样,我假设如果@Valid失败,我会得到某种4xx响应,但这似乎没有发生. 这里遗漏了什么?

推荐答案

问题是您可能依赖错误版本的Bean验证API.您包括了该API的v2,但是对于Spring Boot3,您应该依赖于Jakarta EE 9,它需要Bean验证API的v3.

要解决此问题,您需要删除validation-api依赖项.您不需要添加任何东西,因为spring-boot-starter-validation已经包含了正确的验证API依赖项(到hibernate-validator).

删除依赖项后,您必须将导入从javax.validation.*更改为jakarta.validation.*.

Java相关问答推荐

JPackage-results已安装-如何添加系统属性?

Spring安全实现多个SQL表身份验证

强制Mockito返回null而不是emtpy list

JUnit—如何模拟局部变量对象方法调用

在模拟超类中设置非setter属性的值

将关键字与正文中的_Allowed匹配,但带有__Signing可选后缀

对Java中的通配符参数的混淆

如何正确创建序列图?

如何解释Java中for-each循环中对Iterable的强制转换方法引用?

try 将JSON字符串响应从API转换为映射字符串、对象>;时出错

是否在settings.xml中使用条件Maven镜像?

如何从HttpResponse实例获取Entity对象的内容?

找出承载Cargo 的最小成本

如何在字节数组中反转UTF-8编码?

JXBrowser是否支持加载Chrome扩展?

Spring Mapstruct如何获取Lazy初始化实体字段的信息?

Java泛型方法重载

Cucumber中第二个网页的类对象未初始化

Spring Boot应用程序中的自定义constraintvalidator不会被调用

在java中使用SevenZip.openArchive方法后无法删除文件