1.aop
启动类加@EnableAspectJAutoProxy
自定义注解,在实体类中使用表示被脱敏字段
建立aop切面类
可能这里gpt会建议你用@Pointcut("execution(public * com.xx.aop..*.get*(..))")这种方式拦截,这种我试了,拦截不住。猜测在mvc返回的时候,已经不被aop拦住了,除非手动调用。并且get方式还要user成为bean,不值当。直接拦截controller包吧。
2.Jackson
序列化类
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import java.io.IOException;
public class DesensitizeSerializer extends JsonSerializer<String> implements ContextualSerializer {
private SensitiveType type;
private int startInclude;
private int endExclude;
public DesensitizeSerializer() {
this.type = SensitiveType.COMMON;
}
public DesensitizeSerializer(SensitiveType type) {
this.type = type;
}
@Override
public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException, IOException {
switch (type) {
case COMMON:
gen.writeString(MsgDesensitizedUtil.commonStr(value));
break;
case ID_CARD:
gen.writeString(MsgDesensitizedUtil.idCardNum(value));
break;
case PHONE_NUMBER:
gen.writeString(MsgDesensitizedUtil.mobilePhone(value));
break;
case EMAIL:
gen.writeString(MsgDesensitizedUtil.email(value));
break;
default:
throw new RuntimeException("未知脱敏类型");
}
}
@Override
public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) {
if (property != null) {
SensitiveData annotation = property.getAnnotation(SensitiveData.class);
if (annotation != null) {
this.type = annotation.value();
}
}
return this;
}
}
针对多种类型的脱敏枚举类
在实体中添加就行了,不需要把自定义序列化加载到SimpleModule里