spring --(18)异常通知、返回通知、环绕通知

直接上代码,通俗易懂java

package com.test.aop.impl;

import java.util.Arrays;
import java.util.List;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

/**
 * 切面类
 * 1.须要将该类放入到IOC容器中
 * 2.再将它申明为一个切面
 */
@Aspect
@Component
public class LoggingAspect {
	
	//返回通知
	//目标方法正常结束后执行的代码,所以返回通知是能够拿获得目标方法的返回值
	@AfterReturning(value="execution(* com.test.aop.impl.CalculatorImpl.*(int,int))",returning="result")
	public void afterReturning(JoinPoint joinPoint,Object result){
		String methodName = joinPoint.getSignature().getName();
		System.out.println("The method" + methodName + "end with:"+result);
	}
	
	//异常通知
	@AfterThrowing(value="execution(* com.test.aop.impl.CalculatorImpl.div(int,int))",throwing="ex")
	public void AfterThrowing(JoinPoint joinPoint,Exception ex){
		String methodName = joinPoint.getSignature().getName();
		System.out.println("The method" + methodName + "occurs exception:"+ex);	
	}
	
	//环绕通知
	@Around("execution(* com.test.aop.impl.CalculatorImpl.*(int,int))")
	public Object Around(ProceedingJoinPoint proceedingJoinPoint){
		
		Object result = null;
		String methodName = proceedingJoinPoint.getSignature().getName();
		try {
			//前置通知
			System.out.println("The method"+methodName+"begin with:"+Arrays.asList(proceedingJoinPoint.getArgs()));
			result = proceedingJoinPoint.proceed();
			//返回通知
			System.out.println("The method" + methodName + "end with:"+result);
		} catch (Throwable e) {
			//异常通知
			System.out.println("The method" + methodName + "occurs exception:"+e);	
		}
		//后置通知
		System.out.println("The method" + methodName + "end ");
		return result;
	}
}
相关文章
相关标签/搜索