Spring Aop enhancement of Five

@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;
  	}
 }
Published 101 original articles · won praise 3 · Views 2246

Guess you like

Origin blog.csdn.net/S_Tian/article/details/104173206
Recommended