一、通知介绍

1. 前置通知(Before)

  在目标方法执行之前执行的通知。

  前置通知方法,可以没有参数,也可以额外接收一个JoinPoint,Spring会自动将该对象传入,代表当前的连接点,通过该对象可以获取目标对象 和 目标方法相关的信息。

  注意,如果接收JoinPoint,必须保证其为方法的第一个参数,否则报错。

2. 环绕通知(Around)

  在目标方法执行之前和之后都可以执行额外代码的通知。

  在环绕通知中必须显式的调用目标方法,目标方法才会执行,这个显式调用是通过ProceedingJoinPoint来实现的,可以在环绕通知中接收一个此类型的形参,spring容器会自动将该对象传入,注意这个参数必须处在环绕通知的第一个形参位置。

  注:只有环绕通知可以接收ProceedingJoinPoint,而其他通知只能接收JoinPoint。环绕通知需要返回返回值,否则真正调用者将拿不到返回值,只能得到一个null。

  环绕通知有控制目标方法是否执行、有控制是否返回值、有改变返回值的能力。环绕通知虽然有这样的能力,但一定要慎用,不是技术上不可行,而是要小心不要破坏了软件分层的“高内聚 低耦合”的目标。

3. 后置返回通知(AfterReturning)

  在目标方法正常执行完成后执行,如果目标方法抛出异常,则不会执行。

  在后置通知中也可以选择性的接收一个JoinPoint来获取连接点的额外信息,但是这个参数必须处在参数列表的第一个。

4. 最终通知(After)

  在目标方法执行完成后执行,不管是正常执行完成,还是抛出异常都会执行

  最终通知无法得到返回值

  最终通知也可以额外接收一个JoinPoint参数,来获取目标对象和目标方法相关信息,但一定要保证必须是第一个参数。

5. 异常通知(AfterThrowing)

  在目标方法抛出异常时执行的通知。

  可以配置传入JoinPoint获取目标对象和目标方法相关信息,但必须处在参数列表第一位。

  另外,还可以配置参数,让异常通知可以接收到目标方法抛出的异常对象。

二、基于XML配置的通知

xml配置:

<!-- 注册bean 和 切面bean -->
<bean id="cola" class="top.demo.xmlaop.Cola"></bean>
<bean id="aopim" class="top.demo.xmlaop.AopIm"></bean> <!--aop:config标签用来配置有关切面的配置 -->
<aop:config>
<!-- 设置切点表达式 以便下面引用 -->
<aop:pointcut expression="execution(* top.demo.xmlaop.Cola.Open(int))" id="cut"/>
<!-- 配置切面所用的bean 和优先级 -->
<aop:aspect ref="aopim" order="1" >
<!-- 配置切面方法 -->
<aop:before method="beforeCheck" pointcut-ref="cut"/>
<aop:after method="afterCheck" pointcut-ref="cut"/>
<aop:after-returning method="afterReturn" pointcut-ref="cut" returning="res"/>
<aop:after-throwing method="afterThrow" pointcut-ref="cut" throwing="ex"/>
<aop:around method="around" pointcut-ref="cut"/>
</aop:aspect> </aop:config>
public class AopIm {

    /*
* 前置通知
* 注意 可以使用通配符 public void替换成* 表示任何的权限修饰符和返回值 等等等等 。。。。。
* 参数替换成..可以表示不限参数的匹配
* */
public void beforeCheck(JoinPoint joinPoint) {
Signature sig=joinPoint.getSignature(); System.out.println("before at "+sig.getName()+"and arg[0] is "+joinPoint.getArgs()[0]); } /*
*后置通知
*无法获取返回值 。可以通过返回通知获取返回值
*且后置通知无论方法是不是异常都会执行
* */
public void afterCheck(JoinPoint joinPoint) {
Signature sig=joinPoint.getSignature(); System.out.println("After at "+sig.getName()+"and arg[0] is "+joinPoint.getArgs()[0]); } /*
* 返回通知
* */
public void afterReturn(JoinPoint joinPoint,Object res) {
Signature sig=joinPoint.getSignature();
System.out.println("After at "+sig.getName()+"return. res= "+res); } /*
* 异常通知
* 注意如果这个方法的参数:假设异常类型为数学除零的异常
* afterThrow(JoinPoint joinPoint,空指针异常类 ex) 然后我这里写了空指针异常
* 那afterThrow这个方法就执行不了 因为类型不对
* */
public void afterThrow(JoinPoint joinPoint,Exception ex) { Signature sig=joinPoint.getSignature();
System.out.println("After at "+sig.getName()+"Throw. message= ");
System.out.println(ex.getMessage());
} /*
* 环绕通知
* 环绕通知就等于整个代理过程交给你自己处理 连被代理对象的要执行的目标方法要不要执行也取决你
* 上面几个通知比较像 处理目标方法调用的某个时刻的 处理过程
* */
public Object around(ProceedingJoinPoint pJoinPoint) { Object res=null;
String methodName=pJoinPoint.getSignature().getName(); System.out.println(methodName+" 执行前(前置通知)");
try { res=pJoinPoint.proceed();
System.out.println(methodName+" 执行后有结果(返回通知)");
} catch (Throwable e) { System.out.println("异常通知 "+e.getMessage());
}
System.out.println(methodName+" 执行后(后置通知)");
return res;
} }

三、基于注解配置的通知

xml配置:

<!-- 配置自动扫描包 -->
<context:component-scan base-package="spring.aop.helloworld"/> <!-- 让aspectj注解起作用: 自动为匹配的类生成代理对象 -->
<aop:aspectj-autoproxy/>
/*
**
** @Aspect:声明式一个切面
** @Component:加入到ioc容器中
** @Order(2):如果在不同的切面中定义多个通知响应同一个切点,为了控制执行顺序,可以用该注解解决。参数(int 类型)越小优先级越大,越先执行。
** 也可以实现org.springframework.core.Ordered 接口,重写getOrder方法。
**
*/ @Order(2)
@Aspect
@Component
public class LoggingAspect {
/**
* 定义一个方法,用于声明切入点表达式,一般的,该方法中不需要再添加其他的代码。 使用@Pointcut来声明切入点表达式
* 后面的其他通知直接使用方法名来引用当前的切入点表达式
*/
@Pointcut("execution(public int spring.aop.helloworld.ArithmeticCalculator.*(int, int))")
public void declareJoinPointExpression() {
} // 声明该方法是一个前置通知:在目标方法开始之前执行
@Before("declareJoinPointExpression()")
public void beforeMethod(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
List<Object> args = Arrays.asList(joinPoint.getArgs());
System.out.println("The " + methodName + " begins " + " args is: " + args);
} // 后置通知:在目标方法发生之后执行(不论这个方法是否发生了异常)
// 在后置通知中海不能访问目标方法执行的结果
@After("declareJoinPointExpression()")
public void afterMethod(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
List<Object> args = Arrays.asList(joinPoint.getArgs());
System.out.println("The " + methodName + " ends " + methodName + " args is: " + args);
} // 返回通知
@AfterReturning(value = "declareJoinPointExpression()", returning = "result")
public void afterReturning(JoinPoint joinPoint, Object result) {
String methodName = joinPoint.getSignature().getName();
System.out.println("The " + methodName + " ends " + methodName + " return is: " + result);
} // 在目标方法出现异常时,会执行的代码,可以访问到异常的对象,且可以指定在发生特定异常时才会打印
@AfterThrowing(value = "declareJoinPointExpression()", throwing = "ex")
public void afterThrowing(JoinPoint joinPoint, Exception ex) {
String methodName = joinPoint.getSignature().getName();
System.out.println("The " + methodName + " occurs exception " + ex);
} /**
* 环绕通知需要携带ProceedingJoinPoint类型的参数 环绕通知类似于动态代理的全过程: ProceedingJoinPoint
* 类型的参数可以决定是否执行目标方法 且环绕通知必须有返回值,返回值即为目标方法的返回值
*
* @param pjd
*/
@Around("execution(public int spring.aop.helloworld.ArithmeticCalculator.*(..))")
public Object aroundMethod(ProceedingJoinPoint pjd) {
Object result = null;
String methodName = pjd.getSignature().getName();
try {
// 前置通知
System.out
.println("@Around before ----> The " + methodName + " begin with " + Arrays.asList(pjd.getArgs()));
result = pjd.proceed();
// 返回通知
System.out.println("@Around return ----> The " + methodName + " return with " + result);
} catch (Throwable e) {
System.out.println("@Around exception ----> The " + methodName + " occurs exception " + e);
throw new RuntimeException(e);
}
// 后置通知
System.out.println("@Around after ----> The " + methodName + " ends");
return result;
}
}

最新文章

  1. TDR测试原理
  2. DPA 9.1.85 升级到DPA 10.0.352流程
  3. 【转】c# Image获得图片路径的三种方法 winform
  4. winform碎片
  5. SVN和Git的异同
  6. bash shell命令行选项与修传入参数处理
  7. Swift-01 UIWebView加载网页
  8. G面经prepare: Set Intersection &amp;&amp; Set Difference
  9. UITableViewCell Property “icon” cannot be found in forward class object “DJWeiBo”
  10. Multipart Upload with HttpClient 4--reference
  11. SCII码表 键盘常用ASCII码
  12. Web Api中实现Http方法(Put,Post,Delete)
  13. 【拓扑排序】【线段树】Gym - 101102K - Topological Sort
  14. servlet中将值以json格式传入
  15. strchr()
  16. 程序员Web面试之jQuery
  17. Android 基础 (四大组件,五大存储,六大布局)
  18. Python 入门必学的8个知识点
  19. Effective Tensorflow[转]
  20. Linux文件与目录管理(三)

热门文章

  1. 教你用好 Javascript 数组
  2. 关于XSS攻击
  3. T-SQL(SQLSERVER)
  4. Wwise音频解决方案概述
  5. 基于OceanStor Dorado V3存储之数据保护 Hyper 特性
  6. Redis(七)分布式锁
  7. Java生鲜电商平台-供应链模块的设计与架构
  8. 微信小程序自定义tabbar的实现
  9. IOS疯狂基础之观察者模式
  10. 如何在浏览器中运行 VS Code?