一、定义
可以通过预编译方式和运行期动态代理实现在不修改源代码的情况下给程序动态统一添加功能的一种技术。它是与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;
}*/
}