继上一篇文章的基础。
后置通知:在目标方法执行后(无论是否发生异常),执行的通知。
一、代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
package aopimpl; import java.util.Arrays; import java.util.List; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.springframework.stereotype.Component; // 把这个类声明成一个切面: // 1.把这个切面放进ioc容器中 // 2.再声明为一个切面 @Aspect @Component public class loggingaspect { @Before("execution(public int aopimpl.calculator.*(int, int))") public void before(JoinPoint joinPoint) { String methodname = joinPoint.getSignature().getName(); List<Object> list = Arrays.asList(joinPoint.getArgs()); System.out.println("the method " + methodname + " begins with " + list.toString()); } @After("execution(public int aopimpl.calculator.*(int, int))") public void after(JoinPoint joinPoint){ String methodname = joinPoint.getSignature().getName(); System.out.println("the method " + methodname + " ends"); } } |
运行结果:
1 2 3 4 5 6 |
the method add begins with [2, 3] the method add ends 5 the method div begins with [466, 233] the method div ends 2 |
成功显示后置的日志。
既然是无视异常都会执行后置通知,那么我们人工添加个异常,使除数为0。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package aopimpl; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class main { public static void main(String[] args) { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("application.xml"); calculator calculator = applicationContext.getBean(calculator.class); System.out.println(calculator.add(2, 3));; System.out.println(calculator.div(466, 0));; } } |
运行结果:除0错误。
1 2 3 4 5 6 |
Exception in thread "main" the method add begins with [2, 3] the method add ends 5 the method div begins with [466, 0] the method div ends java.lang.ArithmeticException: / by zero |
特别注意:在后置通知中还不能访问目标方法执行的结果,结果只能在返回通知才可以获得哦。
那么问题来了:为什么后置通知不能访问目标方法执行的结果?
因为无论方法是否执行错误,后置通知都会执行,我们不希望让后置通知返回错误信息,所以后置通知不能访问目标方法执行的结果。
二、总结
异曲同工。