文章目录
应用
1.日志 , 并将日志保存进数据库
2.代替filter拦截器(权限验证/安全检查)
3.事务控制(回滚,提交关闭)
一、环绕通知是什么?
环绕通知是SpringAOP最强大的通知 , 底层和编写逻辑都类似于Java原生的动态代理 , 相当于是将前面的四个通知做了合并
二、环绕通知使用步骤
1.准备工作
打上Around
标签,向方法传入ProceedingJoinPoint
参数并获取目标方法执行的参数列表
2.执行
使用Object result = pjp.proceed(args);
执行方法 , 用result接受返回值
3.加上try-catch和throws抛出异常
4.代码
@Around("constPoint()")
public static void logAround(ProceedingJoinPoint pjp) throws Throwable {
// System.out.println("["+joinPoint.getSignature().getName() + "]" + "方法执行完成 ");
Object[] args = pjp.getArgs(); //获取参数列表
String methodName = pjp.getSignature().getName();
try {
System.out.println("环绕["+methodName+ "]" + "方法即将开始执行,参数如下 : "+args);
Object result = pjp.proceed(args); //方法执行
System.out.println("环绕["+methodName+ "]" + "方法正常执行完成,结果如下 : "+result);
} catch (Exception e) {
// TODO: handle exception
System.out.println("环绕["+methodName+ "]" + "方法执行异常,异常如下 : "+e.getCause());
}finally {
System.out.println("环绕["+methodName+ "]" + "方法执行完成 ");
}
三、环绕通知与普通通知的执行顺序
1.如果同时存在环绕通知和普通通知 , 当环绕通知捕获到了异常时 ,
普通通知就不会执行了
2.同时存在二者时 , 环绕通知先执行
四、基于配置的AOP以及使用场景
1.原则 :
重要的目标方法使用配置文件的形式进行AOP切面 , 普通方法使用注解形式配置
2.配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
">
<aop:aspectj-autoproxy/>
<context:component-scan base-package="com.hzyc.lesson">
</context:component-scan>
<!-- 将类注册进容器 -->
<!-- 首字母注意小写 -->
<bean id="goodDaoImpl1" class="com.hzyc.lesson.mapper.GoodDaoImpl1"></bean>
<bean id="logUtils" class="com.hzyc.lesson.service.LogUtils"></bean>
<!-- 指定切面 -->
<aop:config>
<aop:aspect ref="logUtils">
<!-- 抽取可重用的切入点表达式 -->
<aop:pointcut expression="execution(* lesson.mapper.*.*(..))" id="myPointcut"/>
<aop:before method="logStart" pointcut-ref="myPointcut"/>
<aop:after method="logEnd" pointcut-ref="myPointcut"/>
<aop:after-returning method="logReturn" pointcut-ref="myPointcut" returning="result"/>
<aop:after-throwing method="logException" pointcut-ref="myPointcut" throwing="exception"/>
</aop:aspect>
</aop:config>
</beans>