SpringAOP五种通知示例

32 篇文章 1 订阅
19 篇文章 3 订阅

0、切点:

0.1:方法切点:

@Pointcut(value="execution(* cn.xxx.ssm.ssmtemplate.service.*.*(..))")
private void addLog1() {}
@Pointcut(value="execution(* cn.xxx.ssm.ssmtemplate.service.*.*(..))&&args(arg0,arg1)",argNames="arg0,arg1")
private void addLog2(String arg0,String arg1) {}

0.2:注解切点:

@Pointcut("@within(org.springframework.stereotype.Controller)")
private void exceptionProcesser() {}

注:注解切点可以有@target和@within,区别如下:

对象的运行时绑定的方法所属的类必须与被@within或@target中的注解类型所注解的类是同一个类,方法拦截才生效

运行时绑定的方法是指运行时对象动态绑定的方法,一般指override方法。

  • @target要求对象的运行时类型与被注解的类型是同一个类型
  • @within要求对象的运行时类型是被注解的类型的子类

1、前置通知:

@Before(value = "addLog()")
public void beforeMethod(JoinPoint jp) {
	String methodName = jp.getSignature().getName();
	System.out.println("【前置通知】the method 【" + methodName + "】 begins with " + Arrays.asList(jp.getArgs()));
}
@Before(value = "addLog(a,b)",argNames="a,b")
public void beforeMethod(JoinPoint jp,String a,String b) {
	String methodName = jp.getSignature().getName();
	System.out.println("【前置通知】the method 【" + methodName + "】 begins with " + Arrays.asList(jp.getArgs()));
}

2、后置通知

@After(value="addLog()")
public void afterMethod(JoinPoint jp) {
	System.out.println("【后置通知】this is a afterMethod advice...");
}

3、返回通知

@AfterReturning(value = "addLog()", returning="result")
public void afterReturningMethod(JoinPoint jp, Object result) {
	String methodName = jp.getSignature().getName();
	System.out.println("【返回通知】the method 【" + methodName + "】 ends with 【" + result + "】");
}
@AfterReturning(value = "addLog(a,b)", argNames="a,b,result", returning="result")
public void afterReturningMethod(JoinPoint jp, String a, String b,Object result) {
	String methodName = jp.getSignature().getName();
	System.out.println("【返回通知】the method 【" + methodName + "】 ends with 【" + result + "】");
}

4、异常通知

@AfterThrowing(value = "addLog()", throwing = "e")
public void afterThorwingMethod(JoinPoint jp, RuntimeException e) {
	String methodName = jp.getSignature().getName();
	System.out.println("【异常通知】the method 【" + methodName + "】 occurs exception: " + e);
}
@AfterThrowing(value = "addLog(a,b)", argNames="a,b,e", throwing = "e")
public void afterThorwingMethod(JoinPoint jp, String a, String b, RuntimeException e) {
	String methodName = jp.getSignature().getName();
	System.out.println(a);
	System.out.println(b);
	System.out.println("【异常通知】the method 【" + methodName + "】 occurs exception: " + e);
}

5、环绕通知

@Around(value="exceptionProcesser()")
public Object around(ProceedingJoinPoint jp) throws Throwable {
	String methodName = jp.getSignature().getName();
	System.out.println("【环绕通知】the method 【" + methodName + "】 around run");
	return null;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值