You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Validation:嵌套对象CustomerCredentialDto的校验注解选择

Spring Validation嵌套对象校验解决方案

问题场景

在Spring Validation场景下,CustomerDto类包含CustomerCredentialDto类型的成员变量,需要让该变量遵循CustomerCredentialDto内部已定义的校验规则,不清楚该添加何种注解及使用方式。

解决方案

需要在CustomerCredentialDto类型的成员变量上添加**@Valid**注解,该注解会触发嵌套对象的校验逻辑,使得CustomerCredentialDto内部的@NotBlank、@Pattern等校验规则生效。

如果要求customerCredentialDto本身不能为null,还需要配合@NotNull注解一起使用,避免null对象绕过校验。

修改后的代码示例

调整后的CustomerDto类

package com.epam.customerservice.dto;

import com.epam.customerservice.models.Gender;
import com.epam.customerservice.models.IdentityType;

import jakarta.validation.Valid;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Positive;
import lombok.AllArgsConstructor;
import lombok.Data;

@Data
@AllArgsConstructor
public class CustomerDto {

    @NotBlank
    @Pattern(regexp = "^[a-zA-Z0-9]{3,10}$", message = "Username must be alphanumeric of length between 3 and 10")
    private String name;

    @Positive
    @Max(value = 99, message = "Age must be valid")
    private Integer age;

    private Gender gender;

    private IdentityType identityType;
    
    @NotBlank
    private String identityNumber;
        
    // 添加@Valid触发嵌套校验,@NotNull确保对象非null
    @NotNull(message = "Customer credential cannot be null")
    @Valid
    private CustomerCredentialDto customerCredentialDto;

}

CustomerCredentialDto类(无需修改)

package com.epam.customerservice.dto;

import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
import lombok.AllArgsConstructor;
import lombok.Data;

@Data
@AllArgsConstructor
public class CustomerCredentialDto {

    @NotBlank
    @Pattern(regexp = "^[a-zA-Z0-9]{3,10}$", message = "Username must be alphanumeric of length between 3 and 10")
    private String username;

    @NotBlank(message = "Password cannot be blank")
    private String password;

}

注意事项

  • @Valid注解来自jakarta.validation包(Spring Boot 3.x及以上使用该包,Spring Boot 2.x使用javax.validation包)
  • 只有添加了@Valid,嵌套对象内部的校验注解才会被Spring Validation框架识别并执行校验

内容的提问来源于stack exchange,提问作者Shounak Sengupta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 12:55:08