使用方式: Dao层需脱敏方法上加注解 @NeedDecrypt(param = “channelName”) 《channelName为需脱敏字段》
代码:
NeedDecrypt 自定义注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
//作用于对返回值进行脱敏处理的方法上
@Target(value = {ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface NeedDecrypt {
String param() default "";
String length() default "";
}
EncryptAop AOP代理环绕通知
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Component
@Aspect
@Slf4j
public class EncryptAop {
/**
* 定义加密切入点
*/
@Pointcut(value = "@annotation(needDecrypt)")
public void pointcut(NeedDecrypt needDecrypt) {
}
/**
* 命中加密切入点的环绕通知
*
* @param proceedingJoinPoint
* @return
* @throws Throwable
*/
@Around("pointcut(needDecrypt)")
public Object around(ProceedingJoinPoint proceedingJoinPoint,NeedDecrypt needDecrypt) throws Throwable {
log.info("//环绕通知 start");
//获取命中目标方法的入参数
Object result=proceedingJoinPoint.proceed();
desenProcess(result,needDecrypt.param(),needDecrypt.length());
return result;
}
public void desenProcess(Object result,String param,String length) throws IllegalAccessException {
if (result instanceof Map) {
// 处理Map类型的返回值
Map<String, Object> resultMap = (Map<String, Object>) result;
// 打印或进一步处理resultMap
System.out.println("获取到的返回值Map: " + resultMap);
}else if (result instanceof List){
List<Map<String, Object>> resultMap = (ArrayList<Map<String, Object>>) result;
for (Map<String, Object> rs:resultMap){
System.out.println("获取到的返回值List中的map: " + rs.toString());
if (rs.containsKey(param)){
System.out.println("拿到一样的了");
String originalValue = String.valueOf(rs.get(param));
if (originalValue.length() > 5) {
System.out.println("length>5");
String maskedValue = originalValue.substring(0, originalValue.length() - 5) + "*****";
rs.put(param, maskedValue);
}
}
}
System.out.println("获取到的返回值List: " + resultMap.get(0).toString());
}else {
System.out.println("类型:"+result.getClass());
}
}
}