1月6

Spring Aop修改目标方法参数和返回值

| |
17:52编程杂谈  From: 本站原创
使用场景,多个接口的某个或多个参数都是从登录态中获取的,如下的capCode,这里只设计修改入参。
@Order(1)
@Component
@Aspect
@Slf4j
public class CapCodeAspect {

    @Autowired
    private TokenService tokenService;

    public CapCodeAspect() {
    }

    @Pointcut("@annotation(com.xx.oo.annotation.CapCode)")
    private void parameterPointCut() {
    }

    @Around("parameterPointCut()")
    public Object getCapCode(ProceedingJoinPoint joinPoint) {
        try {
            Object[] o = joinPoint.getArgs();
            if (null != o) {
                for (Object ob : o) {
                    changObjectValue(ob, "capCode", gatCapCode());
                }
            }
            return joinPoint.proceed(o);
        } catch (Throwable e) {
            log.error("目标方法执行异常,目标类:" + joinPoint.getTarget() + "方法:" + joinPoint.getSignature().getName(), e);
            throw new RuntimeException("系统繁忙,请稍后再试!");
        }
    }


    /***
     * 修改入参具体字段值
     */
    private Object changObjectValue(Object obj, String filedName, Object afterValue) throws Exception {
        Class<?> resultClz = obj.getClass();
        //获取父类的字段,因为capCode放在在基类里面,这里就直接获取父类的Class了,
//参数只在当前类的可以添加当前类的逻辑
        Field[] fieldInfo = resultClz.getSuperclass().getDeclaredFields();
        for (Field field : fieldInfo) {
            if (filedName.equals(field.getName())) {
                field.setAccessible(true); //成员变量为private,故必须进行此操
                Object fieldValue = field.get(obj);
                field.set(obj, afterValue);
                break;
            }
        }
        return obj;
    }


    private String gatCapCode() {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        String capCode = user.getProviderId();
        log.info("资金编码:{}", capCode);
        return capCode;
    }


}


来源:Heck's Blog
地址:https://www.heckjj.com/post/580/
转载时须以链接形式注明作者和原始出处及本声明,否则将追究法律责任,谢谢配合!
阅读(29) | 评论(0) | 引用(0)