Spring Boot AOP切面验证登陆
此文只说明在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切面的底层原理,文章如果有错误欢迎指出,一起成长
相关推荐
zmysna 2020-06-25
itjavashuai 2020-05-27
neweastsun 2020-05-05
MicroBoy 2020-05-04
方志朋 2020-05-01
横云断岭 2020-04-17
方志朋 2020-03-01
smalllove 2020-02-14
csuzxm000 2020-01-09
neweastsun 2019-12-29
82296830 2014-06-07
whbing 2019-12-08
Julywhj 2019-12-04
JudeJoo 2019-11-19
Julywhj 2019-10-28
凯哥Java 2019-10-26
kimlunarove 2015-02-26
whileinsist 2019-08-16
MayMatrix 2018-04-15