Spring AOP——结果通知&&异常通知&&环绕通知

package com.dhx.spring.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;

//把这个类声明为一个切面:需要把该类放到IOC容器中,再声明为一个切面
@Aspect
@Component
public class LoggingAspect {
	
	/*//声明该方法是一个前置通知:在目标方法开始之前执行,其中*为具体的某个方法名,也可以指全部的方法名
	@Before("execution(public int com.dhx.spring.aop.impl.ArtithmeticCalculatorImpl.*(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("execution(public int com.dhx.spring.aop.impl.ArtithmeticCalculatorImpl.*(int, int))")
	public void afterMethod(JoinPoint joinPoint) {
		//方法名
		String methodName=joinPoint.getSignature().getName();
		System.out.println("the method "+methodName+" ends");
	}
	
	//在方法正常结束受执行的代码
	//返回通知是可以访问到方法的返回值的
	@AfterReturning(value="execution(public int com.dhx.spring.aop.impl.ArtithmeticCalculatorImpl.*(int, int))",
			returning="result")
	public void afterReturningMethod(JoinPoint joinPoint,Object result) {
		//方法名
		String methodName=joinPoint.getSignature().getName();
		System.out.println("the method "+methodName+" ends with "+result);
	}
	
	
	
	 * 在目标方法出现异常时会出现的代码
	 * 可以访问到异常对象,且可以指定在出现特定异常时在执行通知异常代码(NullPointerException ex)
	 
	@AfterThrowing(value="execution(public int com.dhx.spring.aop.impl.ArtithmeticCalculatorImpl.*(int, int))",
		throwing="ex")
	public void afterThrowing(JoinPoint joinPoint,Exception ex) {
		//方法名
		String methodName=joinPoint.getSignature().getName();
		System.out.println("the method "+methodName+"occurs execption"+ex);
	}
	*/
	
	/*
	 * 环绕通知需要携带ProceedingJoinPoint类型的参数
	 * 环绕通知类似于动态代理的全过程:ProceedingJoinPoint类型的参数可以决定是否执行目标方法
	 * 且环绕通知必须有返回值,返回值即为目标方法的返回值
	 */
	@Around("execution(public int com.dhx.spring.aop.impl.ArtithmeticCalculatorImpl.*(int, int))")
	public Object aroundMethod(ProceedingJoinPoint pjd) {
		Object result=null;
		String methodName=pjd.getSignature().getName();//方法名
		try {
			//前置通知
			System.out.println("the method "+methodName+" begins with "+Arrays.asList(pjd.getArgs()));
			result=pjd.proceed();
			//结果通知
			System.out.println("the method"+methodName+" ends "+result);
		} catch (Throwable e) {
			//异常通知
			System.out.println("the method "+methodName+" occurs execption:"+e);
			throw new RuntimeException(e);
		}
		//后置通知
		System.out.println("the method "+methodName+" ends");
		return result;
	}
}

猜你喜欢

转载自blog.csdn.net/qq_39093474/article/details/86686330