1、AOP基本总结
连接点(
JoinPoint
):连接点是程序运行的某个阶段点,如方法调用、异常抛出等
切入点(
Pointcut
):切入点是
JoinPoint
的集合
是程序中需要注入Advice
的位置的集合,即Advice
在什么条件下才能被触发增强(
Advisor
):增强是切入点
Pointcut
和Advice
的综合体,即在连接点JoinPoint
上执行的行为
通过JDK/CGLIB
代理模式实现AOP切面(
Aspect
):@Aspect通常是一个类的注解,通常与
@Component
搭配使用AOP代理(
AOP Proxy
):AOP使用动态代理模式创建对象,从而实现在连接点
JoinPoint
处插入增强
其中JDK本文来源gao@!dai!ma.com搞$$代^@码网*只能代理接口,CGLIB基于子类但不能代理final类
2、常用方法
3、增强类型
@Before
:前置增强,在某个JoinPoint
执行前的增强@After
:final增强,不管抛异常还是正常退出都执行的增强@AfterReturning
:后置增强,方法正常退出时执行@AfterThrowing
:异常抛出增强,抛出异常后执行@Around
:环绕增强,包围一个连接点的增强,最强大的一个方式,且常用
4、示例说明
学了一下AOP的使用,写了个@Around
的demo
,将几个查询操作存入数据库作为Log
并且定时清理过期数据
本人的Demo
用的是Dubbo
框架,而AOP的示例写在了Provider
中,大概结构如下:
monitor:
annotation
:注解类aop
:切面的定义及实现impl
:UserAopTask接口的实现类
1)UserLog
实体类
@Data @ToString @NoArgsConstructor @AllArgsConstructor public class UserLog implements Serializable { private Integer id; private String methodName; private String methodArgs; private String classFullName; private String className; private Date invokeTime; private Double costTime; }
2)LogTaskMapper
对应mapper
接口
public interface LogTaskMapper { /** * TEST AOP INSERT INFO INTO TABLE * @param userLog */ void insertUserLog(UserLog userLog); /** * DELETE LOGS IN TABLE LAST x MINUTES * @param minutes */ void deleteUserLog(int minutes); }
3)UserAopTask
接口
public interface UserAopTask { void insertUserLog(UserLog log); }