AOP:Aspect Oriented Programming (面向切面编程、面向方面编程),其实就是面向特定方法编程
依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
@Component
@Aspect
@Slf4j
public class TimeAspect {
@Around("execution(* com.example.demo.service.*.*(..))")
public Object recordTime(ProceedingJoinPoint joinPoint) throws Throwable {
long begin = System.currentTimeMillis();
Object result = joinPoint.proceed();
long end = System.currentTimeMillis();
log.info(joinPoint.getSignature()+"用时:{}",end-begin);
return result;
}
}
切入点表达式
@Pointcut("execution(* com.example.demo.service.*.*(..))")
private void pt(){}
@Around("pt()")
类名靠前先执行
也可以用@Order(数字)来控制,数字越小越先执行。
通配符
切入点表达式书写建议
@Retention(RetentionPolicy.RUNTIME)//运行时
@Target(ElementType.METHOD)//方法上
public @interface MyLog {
}
@Pointcut("@annotation(com.example.demo.aop.MyLog)")
//获取目标对象类名
String name = joinPoint.getTarget().getClass().getName();
log.info("1:{}",name);
//获取目标对象的方法名
String name1 = joinPoint.getSignature().getName();
log.info("2:{}",name1);
//获取目标对象运行时传入的参数
Object[] args = joinPoint.getArgs();
log.info("3:{}", Arrays.toString(args));
//放行目标方法的执行
Object result = joinPoint.proceed();
//获取目标方法运行时的返回值
切面 类获取网络请求jwt令牌
@Component
@Aspect
@Slf4j
public class TimeAspect {
@Autowired
HttpServletRequest request;
@Pointcut("@annotation(com.example.demo.aop.MyLog)")
private void pt(){}
@Around("pt()")
public Object recordTime(ProceedingJoinPoint joinPoint) throws Throwable {
String jwt = request.getHeader("token");
Claims claims = JwtUtils.parseJwt(jwt);
Object result = joinPoint.proceed();
return result;
}
}