我们在写 OAuth2Filter 的时候,把更新后的令牌写到 ThreadLocalToken 里面的 ThreadLocal 。那么这个小节,我们要创建 AOP 切面类 ,拦截所有 Web 方法的返回值,在返回的 R对象 中添加更新后的令牌。

    1. package com.project.emos.wx.aop;
    2. import com.project.emos.wx.common.util.R;
    3. import com.project.emos.wx.config.shiro.ThreadLocalToken;
    4. import org.aspectj.lang.ProceedingJoinPoint;
    5. import org.aspectj.lang.annotation.Around;
    6. import org.aspectj.lang.annotation.Aspect;
    7. import org.aspectj.lang.annotation.Pointcut;
    8. import org.springframework.beans.factory.annotation.Autowired;
    9. import org.springframework.stereotype.Component;
    10. import org.springframework.web.context.annotation.ApplicationScope;
    11. /**
    12. * @author JianqingWeng
    13. * @Description
    14. * @create 2021-06-18 21:01
    15. */
    16. @Aspect
    17. @Component
    18. public class TokenAspect {
    19. @Autowired
    20. private ThreadLocalToken threadLocalToken;
    21. @Pointcut("execution(public * com.project.emos.wx.controller.*.*(..)))")
    22. public void aspect() {
    23. }
    24. @Around("aspect()")
    25. public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
    26. // 获取方法执行结果
    27. R r = (R) joinPoint.proceed();
    28. String token = threadLocalToken.getToken();
    29. // 如果 ThreadLocal 中存在 Token, 说明是更新的 Token
    30. if (token != null) {
    31. // 往响应中放置 token
    32. r.put("token", token);
    33. threadLocalToken.clear();
    34. }
    35. return r;
    36. }
    37. }