aop 面向切面编程

一、定义

可以通过预编译方式和运行期动态代理实现在不修改源代码的情况下给程序动态统一添加功能的一种技术。它是与oop(面向对象编程)互补使用。 它有前置通知、后置通知、环绕通知、异常通知,白话来说就是源代码执行前后你想干点什么。

二、使用场景

:不使用redis实现用户的权限认证,邮箱密码找回等等,原函数执行邮箱验证完需要重新生成token,设置新的失效时间(5分钟)

三、使用:

1、导包: boot的aop包

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>
@Component
@Aspect
public class MyAop {   //修饰符 包 .类.方法(参数)  ..表示不管参数
    /*@Before("execution(* com.neuedu.controller.*.*(..))")  //execution放入哪些方法使用,这里涉及到匹配规则
    public void before() {
        System.out.println("方法前,前置通知");
    }*/
    @AfterReturning(value = "execution(* com.neuedu.controller.*.*(..))",returning = "result")
    public ResultData after(ResultData result) {   //result是源代码返回的一摸一样
        // 拿出原先的token
        // 想拿原先的token 必须有 HttpServletRequest对象
        System.out.println("后置通知");
        ServletRequestAttributes requestAttributes =(ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String token = request.getHeader("token");
        // 解析token 拿到 用户id 和密码
        JwtUtil jwtUtil = JwtUtil.deToken(token);
        // 生成新token
        String newtoken = JwtUtil.createTokenBySession(jwtUtil.getUserid(),jwtUtil.getPwd());
        result.setToken(newtoken);
        return result;


    }  
   /* @Around(value = "execution(* com.neuedu.controller.*.*(..))") //环绕通知
    public ResultData around(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("方法前");
        ResultData resultData = (ResultData) joinPoint.proceed();
        resultData.setToken("fdjkslajfkldsjafkldsjla");
        System.out.println("方法后");
        return resultData;
    }*/
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值