Spring-Boot-AOP切面验证登陆

12次阅读

共计 1090 个字符,预计需要花费 3 分钟才能阅读完成。

此文只说明在 Spring Boot 中如何使用 AOP 切面,让自己专注业务逻辑代码

代码展示

@Aspect
@Component
@Slf4j
public class SellerAuthorizeAspect {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Pointcut("execution(public * com.example.demo.controller.Seller*.*(..))"+
            "&& !execution(public * com.example.demo.controller.SellerUserController.*(..))")
    public void verify(){}

    @Before("verify()")
    public void doverify(){ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        Cookie cookie = CookieUtil.get(request, CookieConstant.TOKEN);
        if(cookie == null){log.warn("【登录校验】Cookie 中查不到 token");
            throw new SellerAuthorizeException();}

        String tokenValue = redisTemplate.opsForValue().get(String.format(RedisConstant.TOKEN_PREFIX, cookie.getValue()));
        if (StringUtils.isEmpty(tokenValue)){log.warn("【登录校验】Redis 中查不到 token");
            throw new SellerAuthorizeException();}
    }
}

代码分析

注解

  • @Aspect 定义一个切面类
  • @Component 注入 Spring 容器
  • @Slf4j lombok 插件下的日志注解
  • @Pointcut 指定切入点表达式
  • @Before 在目标方法前执行(还有其他的注解,如 @After、@AfterReturning、@AfterThrowing、@Around)

逻辑代码

在注解 @Before 编辑自己的逻辑函数即可

展望

以后会好好看看 Spring AOP 切面的底层原理,文章如果有错误欢迎指出,一起成长

正文完
 0