1. 程式人生 > >後置通知,返回通知,異常通知,環繞通知

後置通知,返回通知,異常通知,環繞通知

@Aspect
@Component
public class LoggingAspect 
{
	//該方法是一個前置通知:在目標方法開始前執行
	@Before("excution(public 返回型別.包名.類名.方法名(int,int))")
	public void beforeMethod(JoinPoint joinpoint){
		String methodName = joinPoint.getSignature().getName();
		List<Object> args = Arrays.asList(JoinPoint.getArgs());

		System.out.println("The Method" + methodName + "begins with:" + args);
	}
	//後置通知:不論該方法是否異常都執行
	@After("excution(public 返回型別.包名.類名.方法名(int,int))")
	public void afterMethod(JoinPoint joinpoint){
		String methodName = joinPoint.getSignature().getName();

		System.out.println("The Method" + methodName + "ends" );
	}
	//返回通知:在方法正常結束時執行,可以訪問到方法的返回值
	@AfterReturning(value = "excution(public 返回型別.包名.類名.方法名(int,int))",returning="result")
	public void afterReturning(JoinPoint joinpoint,Object result){
		String methodName = joinPoint.getSignature().getName();

		System.out.println("The Method" + methodName + "ends with:" + result );
	}
	//異常通知:可以訪問到異常物件,且可以指定在出現特定異常時再執行
	@AfterThrowing(value = "excution(public 返回型別.包名.類名.方法名(int,int))",throwing="ex")
	public void afterThrowing(JoinPoint joinpoint,Exception ex){
		String methodName = joinPoint.getSignature().getName();

		System.out.println("The Method" + methodName + "occurs excetion:" + result );
	}
	//環繞通知:需攜帶ProceedingJoinPoint型別引數,類似動態代理中的全過程
	//環繞通知必須有返回值
	@Around("excution(public 返回型別.包名.類名.方法名(int,int))")
	public Object aroundMethod(ProceedingJoinPoint pjd){
		Object result = null;
		String methodName = joinPoint.getSignature().getName();

		try{
			//前置通知
			System.out.println("The method" + ,methodName+"begins with"+Array.asList(pjd.getArgs()));
			//執行目標方法
			result = pjd.proceed();
			//後置通知
			System.out.println("The method "+ methodName +"ends with:" + result);
		}catch (Throwable e){
			//異常通知
			System.out.println("The Method " +methodName+ "occurs excetion:" + e );
		}
		//後置通知
		System.out.println("The Method" + methodName + "ends" );

		return result;
	}
}