枚举脱敏字段类型及规则
import java.util.function.Function;
public enum TextMaskStrategy {
ID_NO("身份证", 18, text -> "*".repeat(text.length() - 4) + text.substring(text.length() - 4)),
PHONE("手机号", 11, text -> text.substring(0, 3) + "*".repeat(text.length() - 7) + text.substring(text.length() - 4)),
BANK_CARD_NO("银行卡号", 10, text -> "*".repeat(text.length() - 8) + text.substring(text.length() - 4)),
ADDRESS("地址", 8, text -> text.substring(0, 5) + "*".repeat(text.length() - 8) + text.substring(text.length() - 3)),
CAR_NO("车牌号", 6, text -> text.substring(0, 2) + "*".repeat(text.length() - 3) + text.substring(text.length() - 1));
private final String textType;
private final int minLength;
private final Function<String, String> maskFunction;
TextMaskStrategy(String textType, int minLength, Function<String, String> maskFunction) {
this.textType = textType;
this.minLength = minLength;
this.maskFunction = maskFunction;
}
public String getTextType() {
return textType;
}
public int getMinLength() {
return minLength;
}
public Function<String, String> getMaskFunction() {
return maskFunction;
}
}
注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@JacksonAnnotationsInside
@JsonSerialize(using = TextMaskJsonSerializer.class)
public @interface TextMask {
TextMaskStrategy strategy();
}
序列化器
public class TextMaskJsonSerializer extends JsonSerializer<String> implements ContextualSerializer {
private TextMaskStrategy strategy;
@Override
public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
if (value != null && value.length() >= strategy.getMinLength()) {
gen.writeString(strategy.getMaskFunction().apply(value));
} else {
gen.writeString(value);
}
}
@Override
public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
TextMask annotation = property.getAnnotation(TextMask.class);
if (Objects.nonNull(annotation)
&& Objects.equals(String.class, property.getType().getRawClass())) {
this.strategy = annotation.strategy();
return this;
}
return prov.findValueSerializer(property.getType(), property);
}
}
使用
在需在脱敏的字段上加上注解并指定脱敏策略
@TextMask(strategy = TextMaskStrategy.BANK_CARD_NO)
private String bankCardNo;
标签:Jackson,String,text,strategy,substring,length,序列化,public,脱敏
From: https://www.cnblogs.com/jiayuan2006/p/18222263