***自定义注解切面,实现对方法的拦截***
1. 自定义一个注解
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Desensitized {
String[] functionCode() default {};
String functionName() default "";
}
2. 对注解实现切面拦截
定义一个类:
@Slf4j
@Aspect
@Component
public class DesensitizedAspect {
//定义切点,注解为Desensitized的都为切入点
@Pointcut("@annotation(com.aexpec.elp.clientuser.util.annotation.Desensitized)")
public void anyDesensitizedAspect() {
//切点
}
@Around("anyDesensitizedAspect()")
public Object isAllowed(ProceedingJoinPoint joinPoint) throws Throwable {
Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
Desensitized desensitized = AnnotationUtils.findAnnotation(method, Desensitized.class);
if (desensitized != null) {
//解密
String[] strings = desensitized.functionCode();
switch (MethodEnum.valueOf(strings[0])) {
case USER:
return DecodeUtil.decodeUser((ClientUserModel) joinPoint.proceed());
case CARD:
return DecodeUtil.decodeCard((ClientUserCardModel) joinPoint.proceed());
case ALIPAY:
return DecodeUtil.decodeAlipayUser((AlipayAppUserModel) joinPoint.proceed());
case HOLDER:
return DecodeUtil.decodeCardHolder((CardholderModel) joinPoint.proceed());
case CARDS:
return DecodeUtil.decodeCardList((List<ClientUserCardModel>) joinPoint.proceed());
default:
break;
}
}
return null;
}
private enum MethodEnum {
USER,
CARD,
ALIPAY,
HOLDER,
CARDS
}
}
@Around(“anyDesensitizedAspect()”) 环绕通知:配合使用ProceedingJoinPoint joinPoint
通过joinPoint.proceed() 获取方法的返回值,再将其强转为需要的实体。
3. 对注解使用
在要拦截的方法前面添加代码
@Desensitized(functionCode = {"CARD"}, functionName = "卡解密")