回环通知是5个通知里的最后一个,与之前的4个相比,它比较与众不同。前面4个分别针对目标方法的一个时间点进行调用。而回环调用更像是前面4中综合起来的另一种替代方案。
回环调用如果非要拿过来对比,其实更像我们之前用过的动态代理的实现方式。我们可以控制目标方法的调用,并且目标方法执行的前后各个时间点插入我们需要执行的代码,已达到前置通知、后置通知、异常通知、返回通知的效果。
环绕通知是所有通知类型中功能最为强大的, 能够全面地控制连接点. 甚至可以控制是否执行连接点.
对于环绕通知来说, 连接点的参数类型必须是 ProceedingJoinPoint . 它是 JoinPoint 的子接口, 允许控制何时执行, 是否执行连接点.
在环绕通知中需要明确调用 ProceedingJoinPoint 的 proceed() 方法来执行被代理的方法. 如果忘记这样做就会导致通知被执行了, 但目标方法没有被执行.
注意: 环绕通知的方法需要返回目标方法执行之后的结果, 即调用 joinPoint.proceed(); 的返回值, 否则会出现空指针异常
(本文出自:http://my.oschina.net/happyBKs/blog/483724)
好,我们还是用例子说话吧。
下面是切面类,我把前面四种通知也保留了,为的是对比一下回环通知的执行顺序。
package com.happBKs.spring.aopbasic.aop1;
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;
@Aspect
@Component
public class LoggingAspect {
/*
* 在com.happBKs.spring.aopbasic.aop1.AtithmeticCalculate接口的每一个实现类的每一个方法开始之前执行
*/
@Before("execution(public int com.happBKs.spring.aopbasic.aop1.AtithmeticCalculate.*(..))")
public void beforeMethod(JoinPoint joinPoint)
{
String methodName=joinPoint.getSignature().getName();
List<Object> args=Arrays.asList(joinPoint.getArgs());
System.out.println("begin to "+methodName+" with "+args);
}
/*
* 在目标方法执行之后(无论是否发生异常),执行该通知
*/
@After("execution(public int com.happBKs.spring.aopbasic.aop1.AtithmeticCalculate.*(..))")
public void afterMethod(JoinPoint joinPoint)
{
String methodName=joinPoint.getSignature().getName();
System.out.println("end to "+methodName);
}
/*
* 在目标方法正常执行之后执行的代码
* 返回通知是可以访问目标方法的返回值的
*/
@AfterReturning(value="execution(public int com.happBKs.spring.aopbasic.aop1.AtithmeticCalculate.*(..))", returning="resultParam")
public void afterReturning(JoinPoint joinPoint, Object resultParam)
{
String methodName=joinPoint.getSignature().getName();
System.out.println("after "+methodName+" with returning result "+resultParam);
}
/*
* 在目标方法出现异常时出现代码
* 可以访问到异常对象,且可以指定在特定异常时才执行代码
*/
@AfterThrowing(value="execution(public int com.happBKs.spring.aopbasic.aop1.AtithmeticCalculate.*(..))", throwing="exThrowing")
public void afterThrowing(JoinPoint joinPoint, Exception exThrowing)
{
String methodName=joinPoint.getSignature().getName();
System.out.println("after exception of "+methodName+" we find the exception is "+exThrowing);
}
/*
* 回环通知需要携带ProceedingJoinPoint类型参数
* 回环通知类似于动态代理的全过程:ProceedingJoinPoint类型的参数可以决定是否执行目标方法
* 且回环通知必须有返回值,返回值即为目标方法的返回值
*/
@Around(value="execution(public int com.happBKs.spring.aopbasic.aop1.AtithmeticCalculate.*(..))")
public Object roundingMethod(ProceedingJoinPoint pjp)
{
Object result=null;
String methodName=pjp.getSignature().getName();
try {
//前置通知
System.out.println("Around: Begin Method"+methodName+" executed with "+Arrays.asList(pjp.getArgs()));
result= pjp.proceed();
//返回通知
System.out.println("Around: Return Method"+methodName+" with result"+result);
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
//异常通知
System.out.println("Around: Exception in "+methodName+":"+e );
}
//后置通知
System.out.println("Around: end Method"+methodName);
return 100;
}
}
回环通知的参数是一个ProceedingJoinPoint参数,它能够控制目标方法的调用,然后我们就可以像动态代理AOP那样写代码了。
这里需要注意,回环通知需要返回Object值。
配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">
<context:component-scan base-package="com.happBKs.spring.aopbasic.aop1"></context:component-scan>
<!-- 使用AspectJ注解起作用。自动为匹配的类生成代理对象 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
测试代码:
package com.happBKs.spring.aopbasic;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.happBKs.spring.aopbasic.aop1.AtithmeticCalculate;
public class TestSpringAOP {
@Test
public void testSpringAOP()
{
//1. 创建spring 的 IOC 容器
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
//2. 从IOC容器获取bean实例
AtithmeticCalculate atithmeticCalculate = (AtithmeticCalculate)ac.getBean(AtithmeticCalculate.class);
//考察一下代理对象是否生成
System.out.println(atithmeticCalculate.getClass().getName());
//3. 使用bean
System.out.println("Example 1:");
int result=atithmeticCalculate.add(10, 5);
System.out.println(result);
System.out.println("\r\nExample 2:");
int result2=atithmeticCalculate.div(10, 0);
System.out.println(result2);
}
}
输出结果:
com.sun.proxy.$Proxy12
Example 1:
Around: Begin Methodadd executed with [10, 5]
begin to add with [10, 5]
Around: Return Methodadd with result15
Around: end Methodadd
end to add
after add with returning result 100
100
Example 2:
Around: Begin Methoddiv executed with [10, 0]
begin to div with [10, 0]
java.lang.ArithmeticException: / by zero
at com.happBKs.spring.aopbasic.aop1.AtithmeticCalculateImpl.div(AtithmeticCalculateImpl.java:24)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.aop.framework.adapter.MethodBeforeAdviceInterceptor.invoke(MethodBeforeAdviceInterceptor.java:52)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:85)
at com.happBKs.spring.aopbasic.aop1.LoggingAspect.roundingMethod(LoggingAspect.java:79)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:621)
at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:610)
at org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroundAdvice.java:68)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.aspectj.AspectJAfterAdvice.invoke(AspectJAfterAdvice.java:43)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.adapter.AfterReturningAdviceInterceptor.invoke(AfterReturningAdviceInterceptor.java:52)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke(AspectJAfterThrowingAdvice.java:58)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy12.div(Unknown Source)
at com.happBKs.spring.aopbasic.TestSpringAOP.testSpringAOP(TestSpringAOP.java:24)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Around: Exception in div:java.lang.ArithmeticException: / by zero
Around: end Methoddiv
end to div
after div with returning result 100
100