一句话
增强版自定义一键脱敏
业务痛点和需求
在风控平台日志追踪实战:基于双AOP+TraceId的全链路解决方案,实现基础脱敏功能。
进而发现我们在不同场景有更深度的脱敏需求,例如:
在投行交易系统与对公贷款风控计算场景中,涉及大量敏感数据:
- 投行交易场景:客户身份证号、交易金额、持仓明细等。
- 对公贷款场景:企业财报数据、法人证件号、抵押物估值等。
架构设计和代码实现
1. 自定义脱敏数据类型枚举
public enum SensitiveType {
ID_CARD,
MOBILE,
AMOUNT,
CUSTOM // 自定义正则表达式
}
2. 自定义脱敏注解
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD})
public @interface Sensitive {
SensitiveType type();
String pattern() default ""; // 正则表达式(CUSTOM类型时生效)
}
3. 策略执行层
实现策略模式,每个枚举对应一个处理类:
public interface SensitiveStrategy {
String process(String value, String pattern);
}
@Component
public class IdCardStrategy implements SensitiveStrategy {
// 具体的process实现
}
4. 拦截处理层(AOP)
通过切面拦截注解,动态选择策略执行脱敏:
@Aspect
@Component
public class SensitiveAspect {
@Around("@annotation(sensitive)")
public Object doSensitive(ProceedingJoinPoint pjp, Sensitive sensitive) throws Throwable {
Object result = pjp.proceed();
return applyStrategy(result, sensitive.type(), sensitive.pattern());
}
}