定义脱敏注解
import java.lang.annotation.*;
@Documented
@Target({ElementType.FIELD,ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface EncryptField {
}
定义脱敏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.springframework.stereotype.Component;
import java.lang.reflect.Field;
import java.util.Arrays;
/**
* 使用AOP进行脱敏
*/
@Slf4j
@Aspect
@Component
public class EncryptHandler {
/**
* 环绕通知
* 异常不做处理,不影响controller的逻辑
*/
@Around("execution(* com.gxzn.controller..*.*(..))")
public Object logUpdateUser(ProceedingJoinPoint joinPoint) throws Throwable {
// 目标参数
Object[] args = joinPoint.getArgs();
log.info(Arrays.toString(args));
for (Object arg : args) {
Field[] fields = arg.getClass().getDeclaredFields();
for (Field field : fields) {
if (field.isAnnotationPresent(EncryptField.class)) {
log.info("脱敏字段:{}", field);
field.setAccessible(true);
String value = (String) field.get(arg);
if (value != null) {
log.info("脱敏数据:{}", value);
}
}
}
}
// 调用目标方法,获得返回值
Object result = joinPoint.proceed();
log.info("响应结果:{}", result);
return result;
}
}
使用方式
正常写controller
import com.gxzn.entity.SystemAdminUser;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 测试
*/
@RestController
@RequestMapping("/test")
public class TestController {
@RequestMapping("/demo")
public String demo(@RequestBody SystemAdminUser systemAdminUser) {
System.out.println(systemAdminUser);
Assert.isTrue(false, "方法内出现异常");
return "成功";
}
}