AOP 面向切面编程
搭建环境 需要 9个包 链接: https://pan.baidu.com/s/1M0QQtX0aiYjmFoWayFHoHA 密码: kapc
切面 切点save*() 连接点 通知
切面 可以当成一个类来理解 对多个切点进行统一的前置通知 后置通知
切点PointCut 监控的方法
连接点JoinPoint 方法执行的时候才会发生 当成对象
前置通知 -> save*() -> 后置通知
配置AOP:
<aop:config>
<aop:aspect ref="firstAop">
<aop:before method="befores" pointcut-ref="firstPoint"/> //前置通知
<aop:after method="afters" pointcut-ref="firstPoint"/> //后置通知
<aop:after-returning method="returning" returning="result" pointcut-ref="firstPoint"/> //后置返回通知
<aop:after-throwing method="throwing" throwing="ex" pointcut-ref="firstPoint"/> //后置异常通知
<!-- 根据表达式来 确定我们的方法的监控名单
execution(* com.lanou.service.impl.ServiceImpl.*(..))
第一个*表示所有返回值 第二个*()表示所有方法 括号里面的.. 表示所有参数
-->
<aop:pointcut id="firstPoint" expression="execution(* com.lanou.service.impl.UserServiceImpl.*(..))"/>
</aop:aspect>
</aop:config>
程序执行过程:
1.首先根据切点 进行对应方法的监控
2.然后当监控的方法真正执行的时候
再来找到我们对应的通知 执行通知对应的方法
3.顺序为 前置通知 -> 真正执行的方法 -> 后置通知
有后置返回通知和后置异常通知时 后置返回通知 -> 后置异常通知环绕通知
<aop:config>
<aop:aspect ref="firstAop">
<!-- 环绕通知 -->
<aop:around method="arounds" pointcut-ref="firstPoint"/>
<!-- 根据表达式来 确定我们的方法的监控名单
execution(* com.lanou.service.impl.ServiceImpl.*(..))
第一个*表示所有返回值 第二个*()表示所有方法 括号里面的.. 表示所有参数
-->
<aop:pointcut id="firstPoint" expression="execution(* com.lanou.service.impl.UserServiceImpl.*(..))"/>
</aop:aspect>
</aop:config>
// 环绕通知方法
public void arounds(ProceedingJoinPoint joinPoint) {
try {
System.out.println("前置通知");
Object result = joinPoint.proceed();
System.out.println("result:" + result);
System.out.println("后置返回通知");
} catch (Throwable e) {
// TODO Auto-generated catch block
System.out.println("后置异常通知");
e.printStackTrace();
} finally {
System.out.println("后置通知");
}
}