SpringBoot项目中,AOP的使用

Springboot中自带依赖

1.创建一个SellerAuthorizeAspect类,打上标签@Aspect和@Component

@Aspect
@Component
@Slf4j
public class SellerAuthorizeAspect {
}

2.设置切点,这个注解的意思是拦截所有controller中Seller*开头的类的方法但是不拦截SellerUserController中的方法

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

3.设置拦截后的操作,这里可以直接处理,也可以抛出一个异常来,然后拦截处理

    @Before("verify()")
    public void doVerify() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //查询cookie
        Cookie cookie = CookieUtil.get(request, CookieConstant.TOKEN);
        if (cookie == null) {
            log.warn("【登录校验】 cookie中没有token");
            throw new SellerAuthorizeException();
        }
        //查询redis
        String tokenValue = redisTemplate.opsForValue().get(String.format(RedisConstant.TOKEN_PREFIX, cookie.getValue()));
        if(StringUtils.isEmpty(tokenValue)){
            log.warn("【登录校验】 redis中没有token");
            throw new SellerAuthorizeException();
        }
    }

 

posted @ 2019-01-28 16:43  寻找梦想的大熊  阅读(1154)  评论(0编辑  收藏  举报