springboot @valid 不同接口使用同一个dto时,区分校验不同的属性
在Spring Boot中,你可以通过使用@Valid注解和分组接口(Group Interface)来对同一个DTO应用不同的验证规则,以区分用于不同接口的属性验证。
首先,定义验证分组接口:
public interface ValidationGroup {
interface Create {}
interface Update {}
}
然后,在你的DTO类中使用@Validated注解来指定使用的分组:
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.groups.Default;
import org.springframework.validation.annotation.Validated;
public class MyDto {
private String createField;
private String updateField;
// Getters and Setters
}
在控制器中,你可以在方法参数上指定使用的分组来触发不同的验证规则:
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
public class MyController {
public void createItem(
// Create item logic
}
public void updateItem(
// Update item logic
}
}
默认情况下,没有指定分组的验证会使用Default.class分组。如果你的DTO属性既需要默认验证,也需要在特定情况下进行分组验证,你可以这样定义:
private String updateField;
在这个例子中,updateField将在默认情况和Update.class分组的情况下都进行@NotNull验证。
浙公网安备 33010602011771号