此文只说明在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切面的底层原理,文章如果有错误欢迎指出,一起成长
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。