使用注解+AOP自动解析token并注入Controller参数

使用注解+AOP自动解析token并注入Controller参数

Administrator 71 2021-05-20

注解

/**
 * @Author 梦叶
 * 自动填充UserCurrent
 */
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface FillUserCurrent {
    //接口名称
    String value() default "";
}


AOP组件

/**
 * @Author 梦叶
 */
@Component
@Aspect
public class FillUserCurrentAspcet extends BaseController {

    @Pointcut("@annotation(com.dedou.by.base.annotation.FillUserCurrent)")
    public void fillUserCurrent() {
    }

    @Before("fillUserCurrent()")
    public void fillOperatorDto(JoinPoint joinPoint) throws IllegalAccessException {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String token = request.getHeader("Authorization");
        if (StrUtil.isBlank(token)) {
            throw new BusinessException("无效的token");
        }
        UserCurrent<Object> currentUser = getCurrentUser(token);
        Object[] args = joinPoint.getArgs();
        for (Object arg : args) {
            if (arg instanceof UserCurrent) {
                //简单场景直接注入
                UserCurrent user = (UserCurrent) arg;
                BeanUtil.copyProperties(currentUser, user);
                continue;
            } else if (arg instanceof CommParam) {
                //CommResult场景直接注入
                CommParam commParam = (CommParam) arg;
                Object param = commParam.getParam();
                Class<?> aClass = param.getClass();
                Field[] fields = aClass.getDeclaredFields();
                for (Field field : fields) {
                    if (field.getType() == UserCurrent.class) {
                        //复杂参数场景
                        field.setAccessible(true);
                        field.set(param, currentUser);
                        continue;
                    }
                }
            } else {
                //作为普通参数场景
                Class<?> aClass = arg.getClass();
                Field[] fields = aClass.getDeclaredFields();
                for (Field field : fields) {
                    if (field.getType() == UserCurrent.class) {
                        //复杂参数场景
                        field.setAccessible(true);
                        field.set(arg, currentUser);
                        continue;
                    }
                }
            }
        }
    }
}