使用定义的列表创建 Spring 搜索 DTO
Create a Spring Search DTO with defined list
是否可以创建一个带有验证标签的 DTO,它只接受定义的值列表?例如:
@Getter
@Setter
public class SearchParams {
private String title;
@NotNull
private String type; // type can be only 'approved', 'new' and 'closed'
}
有没有什么方法可以让标签只包含这个严格的值列表?
@Getter
@Setter
public class SearchParams {
private String title;
@NotNull
private TypeEnum type;
}
public enum TypeEnum {
APPROVED,
NEW,
CLOSED
}
您可以使用描述丰富枚举,以便控制区分大小写
public enum TypeEnum {
APPROVED("approved"),
NEW("new"),
CLOSED("closed");
private String desc;
TypeEnum(String desc) {
this.desc = desc;
}
public String getDesc() {
return desc;
}
static TypeEnum fromDesc(String desc) {
TypeEnum[] values = TypeEnum.values();
for (TypeEnum typeEnum: values) {
if (typeEnum.getDesc().equals(desc)) {
return typeEnum;
}
}
return null;
}
}
因此您可以通过小写字符串获取相关枚举:
TypeEnum.fromDesc("new") // this will return TypeEnum.NEW
是否可以创建一个带有验证标签的 DTO,它只接受定义的值列表?例如:
@Getter
@Setter
public class SearchParams {
private String title;
@NotNull
private String type; // type can be only 'approved', 'new' and 'closed'
}
有没有什么方法可以让标签只包含这个严格的值列表?
@Getter
@Setter
public class SearchParams {
private String title;
@NotNull
private TypeEnum type;
}
public enum TypeEnum {
APPROVED,
NEW,
CLOSED
}
您可以使用描述丰富枚举,以便控制区分大小写
public enum TypeEnum {
APPROVED("approved"),
NEW("new"),
CLOSED("closed");
private String desc;
TypeEnum(String desc) {
this.desc = desc;
}
public String getDesc() {
return desc;
}
static TypeEnum fromDesc(String desc) {
TypeEnum[] values = TypeEnum.values();
for (TypeEnum typeEnum: values) {
if (typeEnum.getDesc().equals(desc)) {
return typeEnum;
}
}
return null;
}
}
因此您可以通过小写字符串获取相关枚举:
TypeEnum.fromDesc("new") // this will return TypeEnum.NEW