给前端传入的请求体中值为的 null 的字段设置默认值
212人浏览 / 0人评论
参考
自定义注解 @DefaultValue
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @Author FengHao
* @Date 2024/8/7
* @Description:
**/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE,ElementType.FIELD, ElementType.METHOD})
@Constraint(validatedBy = DefaultValueValidator.class)
public @interface DefaultValue {
boolean isClass() default false;
String value() default "";
String message() default "";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
校验类 DefaultValueValidator.class
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Field;
/**
* @Author FengHao
* @Date 2024/8/7
* @Description:
**/
public class DefaultValueValidator implements ConstraintValidator<DefaultValue, Object> {
private boolean isClass = false;
@Override
public void initialize(DefaultValue constraintAnnotation) {
isClass = constraintAnnotation.isClass();
}
@Override
public boolean isValid(Object obj, ConstraintValidatorContext context) {
if (obj == null || !isClass) {
return true;
}
Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {
if (field.isAnnotationPresent(DefaultValue.class)) {
DefaultValue defaultValue = field.getAnnotation(DefaultValue.class);
String value = defaultValue.value();
field.setAccessible(true);
try {
Object fieldValue = field.get(obj);
if (fieldValue != null && !fieldValue.equals("")) {
continue;
}
String fieldType = field.getType().getSimpleName();
switch (fieldType) {
case "String":
field.set(obj, value);
break;
case "Integer":
field.set(obj, Integer.valueOf(value));
break;
case "Long":
field.set(obj, Long.valueOf(value));
break;
case "Boolean":
field.set(obj, Boolean.valueOf(value));
break;
case "Double":
field.set(obj, Double.valueOf(value));
break;
default:
}
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
return true;
}
}
使用示例
实体类
@Data
@DefaultValue(isClass = true)
public class MyTest {
@DefaultValue(value = "123")
private Integer code;
@DefaultValue(value = "123456")
private Long userId;
@DefaultValue(value = "false")
private Boolean delete;
@DefaultValue(value = "99999.99")
private Double money;
@DefaultValue(value = "0")
private String state = "0";
}
控制类
@PostMapping(value = "/test")
@Transactional(rollbackFor = Exception.class)
public ResponseEntity<Object> censusAddAll(@Validated @RequestBody MyTest mytest) {
System.out.println("mytest = " + mytest);
return new ResponseEntity<>(mytest, HttpStatus.OK);
}
全部评论