后置通知,返回通知,异常通知,环绕通知

@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;
	}
}

猜你喜欢

转载自blog.csdn.net/lky888666/article/details/80657734