一、AOP是什么?
AOP:面向切面编程
AOP底层核心:动态代理
动态代理底层核心: 反射
二、具体实现
1.自定义注解
@Target({ElementType.TYPE,ElementType.METHOD})//注解作用的位置
@Retention(RetentionPolicy.RUNTIME)//注解的生命周期
@Documented//是否添加java文档
public @interface MyAnno {
String value() default "";
}
2.创建切面类
/**
1. AOP类
*/
@Aspect
@Component
public class DSAspect {
@Pointcut("@annotation(com.fdong.springboot.customAnnotation.annotation.MyAnno)")//切入点 自定义注解
public void pointCut(){}
// 前置通知
@Before("pointCut()")
public void doBefore(){
System.out.println("执行了before方法....");
}
//不管有没有异常都执行 最终通知
@After("pointCut()")
public void doAfter(){
System.out.println("执行了after....");
}
//后置通知 完成通知 有异常不执行
@AfterReturning("pointCut()")
public void doAfterReturning(){
System.out.println("执行了doAfterReturning方法....");
}
//异常通知
@AfterThrowing("pointCut()")
public void doAfterThrowing(){
System.out.println("执行AfterThrowing方法....");
}
//环绕通知,灵活添加代码
@Around("pointCut() && @annotation(myAnno)")
public void doAround(ProceedingJoinPoint proceedingJoinPoint, MyAnno myAnno) throws Throwable {
System.out.println("执方法doAround前....");
System.out.println("获得自定义注解参数value:"+myAnno.value());
String methodName = proceedingJoinPoint.getSignature().getName();
System.out.println("注解作用的方法名:"+methodName);
proceedingJoinPoint.proceed();
System.out.println("执方法doAround后....");
}
}
3.使用
- 控制器层
@RestController
public class TestController {
@Autowired
private TestService testService;
@RequestMapping("/test")
public void test(){
System.out.println("***************TestController test");
testService.test();
}
}
2.业务层
@Service
public class TestService {
@MyAnno("执行MyAnno")
public void test(){
System.out.println("执行了TestService中的test方法");
}
}
3.测试结果