Sping中的前置通知,后置通知,返回通知,异常通知,环绕通知(基于注解配置)

package zhang.spring.apo.beans.Aspect;

import java.util.Arrays;

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;

@Aspect
@Component
public class LogginAspect {
	/**
	 * 前置通知:在代理对象调用目标方法之前执行
	 */
	@Before("execution(public int zhang.spring.apo.beans.Mathtools.*(..))")
	public void MethodBefore(JoinPoint joinPoint){
		String methodName = joinPoint.getSignature().getName();
		Object[] args=joinPoint.getArgs();
		System.out.println("The method:"+methodName+" begin with "+Arrays.asList(args)+"(前置通知)");
	}
	/**
	 * 后置通知:在代理对象调用目标方法之后执行,包括调用目标方法出现异常,或者通知依然或正常执行.
	 * @param joinPoint
	 */
	@After("execution(public int zhang.spring.apo.beans.Mathtools.*(..))")
	public void MethodAfter(JoinPoint joinPoint){
		String methodName = joinPoint.getSignature().getName();
		System.out.println("The method:"+methodName+" end(后置通知)");
	}
	/**
	 * 返回通知:在代理对象的目标方法正常执行完成之后执行该方法,可以获取目标方法的返回值
	 */
	@AfterReturning(value="execution(public int zhang.spring.apo.beans.Mathtools.*(..))",returning="result")
	public Object MethodReturning(JoinPoint joinpoint,Object result){
		String methodName=joinpoint.getSignature().getName();
		System.out.println("The method:"+methodName+" begin Return value:"+result+"(返回通知)");
		return result;
	}
	/**
	 * 异常通知:在目标方法执行出现异常的时候执行该方法
	 */
	@AfterThrowing(value="execution(public int zhang.spring.apo.beans.Mathtools.*(..))",throwing="ex")
	public void ExceptionMethod(JoinPoint joinPoint){
		String methodName=joinPoint.getSignature().getName();
		System.out.println("The method:"+methodName+" error:"+"(异常通知)");
	}
	/**
	 * 环绕通知:
	 * @throws Throwable 
	 */
	@Around(value="execution(public int zhang.spring.apo.beans.Mathtools.*(..))")
	public Object AroundMehtod(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
		Object args=proceedingJoinPoint.getArgs();
		Object result=null;
		String methodName=proceedingJoinPoint.getSignature().getName();
		try {
			
			System.out.println("The method:"+methodName+" begin with "+Arrays.asList(args)+"(前置通知)");
			result=proceedingJoinPoint.proceed();
			System.out.println("The method:"+methodName+" begin Return value:"+result+"(返回通知)");
			
		} catch (Exception e) {
			System.out.println("The method:"+methodName+" error:"+"(异常通知)");
		}
		System.out.println("The method:"+methodName+" end(后置通知)");
		return result;
		
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值