我们在写 OAuth2Filter 的时候,把更新后的令牌写到 ThreadLocalToken 里面的 ThreadLocal 。那么这个小节,我们要创建 AOP 切面类 ,拦截所有 Web 方法的返回值,在返回的 R对象 中添加更新后的令牌。
package com.project.emos.wx.aop;import com.project.emos.wx.common.util.R;import com.project.emos.wx.config.shiro.ThreadLocalToken;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.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;import org.springframework.web.context.annotation.ApplicationScope;/*** @author JianqingWeng* @Description* @create 2021-06-18 21:01*/@Aspect@Componentpublic class TokenAspect {@Autowiredprivate ThreadLocalToken threadLocalToken;@Pointcut("execution(public * com.project.emos.wx.controller.*.*(..)))")public void aspect() {}@Around("aspect()")public Object around(ProceedingJoinPoint joinPoint) throws Throwable {// 获取方法执行结果R r = (R) joinPoint.proceed();String token = threadLocalToken.getToken();// 如果 ThreadLocal 中存在 Token, 说明是更新的 Tokenif (token != null) {// 往响应中放置 tokenr.put("token", token);threadLocalToken.clear();}return r;}}
