AOP五种增强(下)

3.返回增强(又称返回通知)
返回增强(又称返回通知):在目标方法正常结束后执行,可以获取目标方法的执行结果

	@AfterReturning(value="execution(int mul(..))",returning="a")
	public void afterReturning(JoinPoint jp,Object a) {
		Object object = jp.getTarget();
		String name= jp.getSignature().getName();
		System.out.println(this.getClass().getName()+":Result of the "+name +" method:"+a);
	}
  • 执行顺序: 前置增强---->目标函数----->后置增强------>返回增强

4.异常增强(又称异常通知)
异常增强(又称异常通知):目标方法抛出异常之后执行,可以访问到异常对象,且可以指定在出现哪种异常时才执行增强代码

	@AfterThrowing(value="execution(int mul(..))", throwing="e")
	public void afterThrowing(JoinPoint jp,Exception e) {
		Object object=jp.getTarget();
		String name= jp.getSignature().getName();
		System.out.println(this.getClass().getName()+":Result of the "+name +" method:"+e);
	}

在目标类中定义一个异常

        @Override
	public int mul(int a, int b) {
		int result = a*b;
		if(result==0) {
			throw new RuntimeException("异常了哈哈哈");
		}
		System.out.println("-->"+result+"写在函数中的result");
		return result;
	}

执行顺序: 前置增强---->目标函数----->后置增强------>异常增强

  1. 前值增强和异常增强只能选一种执行,不能都执行
  2. 目标函数要抛出异常。并且抛出的异常是public void afterThrowing(JoinPoint joinPoint,Exception e)中规定捕获的异常的子类,或者是同样的异常。

5.环绕增强
目标方法执行前后都可以织入增强处理,可以实现以上四种增强

      @Around("execution(int mul(int,int))")
	public Object around(ProceedingJoinPoint jp) {
		Object result=null;
		Object object = jp.getTarget(); //产生代理对象
		Object [] args = jp.getArgs();
		String name= jp.getSignature().getName();
		try {
			try {
				//前置增强
				System.out.println(this.getClass().getName() + ":The " + name + " method begins.");
				System.out.println(this.getClass().getName() + ":Parameters of the "+name +" method: [" + args[0] + "," + args[1] + "]");
				result = jp.proceed();//执行目标对象内的方法
			} finally {
				//后置增强
				System.out.println(this.getClass().getName() + ":The " + name + "method ends.");
			} 
			//返回增强
			System.out.println(this.getClass().getName()+":Result of the "+name +" method:"+result);
		} catch (Throwable e) {
			//异常增强
			System.out.println(this.getClass().getName()+":Result of the "+name +" method:"+e);
		}
		return result;
	}
  • 执行顺序: 前置增强---->目标函数----->后置增强------>返回增强/异常增强

注意:@Before、@After、@AfterRunning和@AfterThrowing修饰的方法没有返回值;而@Around修饰的方法必须有返回值

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值