一、AOP 相关概念
AOP(Aspect Oriented Program) 面向切面编程。
AOP 术语:
通知(Advice):切面要完成的工作以及合适完成执行。
- 前置通知(Before) 实现的接口是MethodBeforeAdvice
- 后置通知(After) 实现的接口是AfterReturningAdvice
- 异常通知(After - throwing) 实现的接口是ThowsAdvice
- 环绕通知(Around) 实现的接口是MethodInterceptor
连接点(Join Point): 程序中需要动态织入的点。
切点(Pointcut):会匹配通知所要织入的一个或多个连接点,解决了在哪个类和 哪些方法的连接点上执行通知的问题。
切面(Aspect):通知和切点的结合。
引入(Introduction):引入允许我们向现有的类添加新的方法或属性,使得程序 具有动态性。
织入(Weaving):把切面应用到目标对象的过程,可以在编译期,类加载期, 运行期进行织入。
Spring 支持的四种实现方式:基于代理的SpringAOP、纯POJO切面、@Aspect注解的驱动切面、注入式Aspect切面。
@Aspect注解:
@Aspec:声明切面
@AfterReturning:通知方法会在目标方法返回后调用
@AfterThrowing:通知方法会在目标方法抛出异常后调用
@Around:通知方法会将目标方法封装起来
@Before:通知方法会在目标方法调用之前执行
@After:通知方法会在目标方法返回或抛出异常后调用
声明公共的切点类:
// 公共的Pointcut声明类
public class MyPointcut {
@Pointcut("execution(* com.apesource.dao.*.*Insert(..))")
public void daoInsertMethodPointcut() {
// 空方法
}
@Pointcut("execution(* com.apesource.dao.*.*Update(..))")
public void daoUpdateMethodPointcut() {
// 空方法
}
使用注解启用AspectJ自动代理:
@Configuration
@ComponentScan
@EnableAspectJAutoProxy // 注册AutoProxyCreator(自动代理工厂)
public class AppConfig {
}
使用AspectJ注解来声明通知方法:
@Before("com.apesource.aspectj.MyPointcut.daoInsertMethodPointcut()")
public void methodBefore(JoinPoint joinpoint){
System.out.println("[日志输出]:--------前置通知开始----------------");
System.out.println("[前置通知]: 目标对象=>" + joinpoint.getTarget());
System.out.println("[前置通知]: 目标方法=>" + joinpoint.getSignature().getName());
System.out.println("[前置通知]: 方法参数=>" + joinpoint.getArgs());
System.out.println("[日志输出]:--------前置通知结束----------------");
}
// "自定义"后置通知方法
@AfterReturning("com.apesource.aspectj.MyPointcut.daoInsertMethodPointcut()")
public void methodAfter(JoinPoint joinpoint){
System.out.println("[日志输出]:--------后置通知----------------");
}