🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# aop的使用 当调用目标方法,跟Aspect中声明的方法相匹配的时候, AOP框架会自动的为目标方法所在的类创建代理对象。 > ## 注解方式 1. 切面注解配置(在spring beans 配置文件中) ``` <aop:aspectj-autoproxy></aop:aspectj-autoproxy> ``` 2. 在相应的切面类中添加注解 @Aspect @Order 表示配置多个切面之间的优先级问题 。谁的值越小谁的优先级越高 。 @Component 3. 表示通知并设置切点 - **标识通知** @Before 前置通知 (JoinPoint) @After 后置通知 (JoinPoint) @AfterReturning 返回通知 (JoinPoint,Object) @AfterThrowing 异常通知 (JoinPoint,Exception) @Around 环绕通知 (上面标识通知的整合) (ProceedingJoinPoint) **tip**:需要调用方法ProceedingJoinPoint的proceed()方法,写在语句前为前置通知, 语句后为后置通知,方法返回值为返回通知,该法方法异常处理为异常通知; 例子 ``` @AfterReturning(value="execution(* com.igeek.service.impl.*.*(..))",returning="sb") public void testAfterReturning(JoinPoint joinpoint,Object sb){ //returning值必须与对象名一致 String method = joinpoint.getSignature().getName(); System.out.println("我是返回通知 。 我在目标方法核心业务执行完才会执行 。"+sb); } 第一个* 表示匹配所有访问修饰符 以及所有返回值类型的方法 第二个* 表示当前包下所有的类 第三个* 表示所有的方法名称 .. 表示匹配任意多个参数。 * (String,.. )表示匹配第一个参数为String类型的方法,..表示匹配任意数量任意类型的参数。 (String,String) 表示匹配参数为两个字符串的方法。 ``` 切点可以通过注解@Pointcut方法配置,避免代码耦合 例子 @Pointcut("execution(* com.igeek.service.impl.*.*(..))") public void declareRepeatJoinPointExpression(){ } - **execution表达式** execution(public * *(..)) 匹配所有类public方法 execution(* com.baidu.dao.*(..)) 匹配指定包下所有类方法,不包含子包 execution(* com.baidu.dao..* (..)) ..* 表示包、子孙包下所有类 execution(* com.baidu.service.UserService.*(..)) 匹配指定类所有方法 execution(* com.baidu.dao.GenericDAO+.*(..)) 匹配实现特定接口所有类方法 execution(* save*(..)) 匹配所有save开头的方法 - **回调属性JoinPoint 属性** `getSignature().getName()`获得调用函数方法名 ` getArgs()`获得参数列表,返回数组 > ## XML方式 1. 引入aop:config标签 2. 配置切点,引入aop:pointcut子标签 `<aop:pointcut expression="execution(* com.igeek.service.impl.*.*(..))" id="pointcut"/>` 3. 配置切面,引入aop:aspect子标签 `<aop:aspect ref="checkAspect" order="1"></aop:aspect> `//ref:指向切面的容器bean的id值 4. 在切面引入标识通知,引入切面子标签aop:before|after... `<aop:before method="checkBeforeLog" pointcut-ref="pointcut"/> //method:触发的通知方法名称 pointcut-ref:映射配置切点的id` 例子 <bean id="checkAspect" class="com.igeek.aspect.CheckAspect"></bean> <aop:config> <aop:pointcut expression="execution(* com.igeek.service.impl.*.*(..))" id="pointcut"/> <aop:aspect ref="checkAspect" order="1"> <aop:before method="checkBeforeLog" pointcut-ref="pointcut"/> </aop:aspect> <aop:aspect ref="loggingAspect" order="2"> <aop:before method="beforeLog" pointcut-ref="pointcut"/> </aop:aspect> </aop:config>