一。什么是AOP
AOP:面向方法编程,在不改变原始方法的基础上,对原始方法进行编程,可以是方法改变和方法减弱,但是AOP只是一种思想,动态代理技术是对AOP的实现
SpringAOP:动态代理是面向切面编程最主流的实现,SpringAOP是Spring框架的高级技术,旨在管理bean对象的过程中,主要通过底层动态代理机制,对特定方法进行编程,
二,怎么使用AOP
1:导入依赖
2:编写AOP程序
三。场景
四。AOP核心概念
* 连接点:Join Point 可以被Aop控制的方法
* 通知:advice,指一些重复的逻辑,也就是共性功能
* Point Cut 匹配连接的条件,通知只会在切入点方法执行时被应用
* 切面:Aspect,描述通知与切入点的关系
* 目标对象:Target,通知所应用的对象
五,AOP进阶
1.通知类型
package com.example.tiaswebmanagement.aop;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
@Aspect
@Component
@Slf4j
public class MyAspect1 {
@Pointcut("execution(* com.example.tiaswebmanagement.service.impl.DeptServiceImpl.*(..))")//抽取出切入点。不仅可以在当前类引用,其他类也可以,注意修饰名
private void pt1(){
}
@Before("pt1()")//直接通过切入点
public void before(){
log.info("before前置通知");
}
@Around("execution(* com.example.tiaswebmanagement.service.impl.DeptServiceImpl.*(..))")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
log.info("around环绕前置通知");
Object result = joinPoint.proceed();
log.info("around后置通知");
return result;
}
@After("execution(* com.example.tiaswebmanagement.service.impl.DeptServiceImpl.*(..))")
public void after(){
log.info("after后置通知");//后置通知
}
@AfterReturning("execution(* com.example.tiaswebmanagement.service.impl.DeptServiceImpl.*(..))")
public void afterReturning(){
log.info("AfterReturning原始方法执行返回后执行这个");
}
@AfterThrowing("execution(* com.example.tiaswebmanagement.service.impl.DeptServiceImpl.*(..))")
public void afterThrowing(){
log.info("AfterThrowing抛出异常后运行");
}
}
注意:环绕通知比较特殊,需要引入ProceedingJoinPoint API
2.通知顺序
3.切入点表达式
4.连接点
package com.example.tiaswebmanagement.aop;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import java.util.Arrays;
@Component
@Slf4j
@Aspect
public class MyAspect8 {
@Pointcut("execution(* com.example.tiaswebmanagement.service.impl.DeptServiceImpl.*(..))")
private void pt1(){}
@Before("pt1()")
public void before(JoinPoint joinPoint){
log.info("MyAspect8...before");
}
@Around("pt1()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
log.info("MyAspect8...aroundbefore");
String name = joinPoint.getTarget().getClass().getName();//获取目标对象类名
log.info("目标方法类名"+name);
String name1 = joinPoint.getSignature().getName();
log.info("方法名"+name1);
Object[] args = joinPoint.getArgs();
log.info("参数"+ Arrays.toString(args));
Object proceed = joinPoint.proceed();
log.info("目标方法返回值"+proceed);
return null;
}
}