Spring Aop中五种增强方法

@Aspect
@Component
public class CalculatorAspect {	
	@Pointcut("execution(public int live.sunhao.calculator.service.CalculatorService.*(..))")
 	public void pointcut() {
 	}
 	
 	//前置增强(又称前置通知):在目标方法执行之前执行
	@Before("execution(public int live.sunhao.calculator.service.CalculatorService.*(..))")
 	public void before(JoinPoint jp) {
  		Object[] args = jp.getArgs();
  		Signature signature = jp.getSignature();
  		System.out.println(signature);
  		String name = signature.getName();
  		System.out.println("The "+name+" method begins.");
  		System.out.println("The "+name+" method args:["+args[0]+","+args[1]+"]");
 	}
 	
	//后置增强(又称后置通知):在目标方法执行后执行,无论目标方法运行期间是否出现异常。注意:后置增强无法获取目标方法执行结果,可以在返回增强中获取
	@After("execution(public int live.sunhao.calculator.service.CalculatorService.*(..))")
 	public void after(JoinPoint jp) {
  		Signature signature = jp.getSignature();
  		String name = signature.getName();
  		System.out.println("The "+name+" method ends.");
 	}

	//返回增强(又称返回通知):在目标方法正常结束后执行,可以获取目标方法的执行结果。方法出现异常时,返回增强不执行
 	@AfterReturning(value = "execution(public int live.sunhao.calculator.service.CalculatorService.*(..))",returning = "result")
 	public void afterReturning(JoinPoint jp,Object result) {
  		Signature signature = jp.getSignature();
  		String name = signature.getName();
  		System.out.println("The "+name+" method result:"+result+".");
 	}

	//异常增强
 	@AfterThrowing(value = "execution(public int live.sunhao.calculator.service.CalculatorService.*(..))", throwing = "e")
 	public void afterThrowing(JoinPoint jp,Exception e) {
  		Signature signature = jp.getSignature();
  		String name = signature.getName();
  		System.out.println("The "+name+" method exception:"+e+".");
 	}

	//环绕增强
	@Around("pointcut()")
 	public Object arround(ProceedingJoinPoint joinPoint) {
  		Object result = null;
  		Object target = joinPoint.getTarget();//目标对象
  		String methodName = joinPoint.getSignature().getName();
  		Object[] params = joinPoint.getArgs();
  		try {
   			try {
    				//前置增强
    				System.out.println(target.getClass().getName()+":The "+methodName+" method begins.");
    				System.out.println(target.getClass().getName()+"Parameters of the "+methodName+"method:["+params[0]+","+params[1]+"]");
    				//执行目标对象的方法
    				result = joinPoint.proceed();
   			}finally {
    				//后置增强
    				System.out.println(target.getClass().getName()+":Result of the "+methodName+" method:"+result);
   			}
  		}catch(Throwable e){
   			//异常增强
   			System.out.println(target.getClass().getName()+":Exception of the method "+methodName+": "+e);
  		}
  		return result;
  	}
 }
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值