自定义注解实现关键字段脱敏

使用方式: 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());
        }

    }



}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值