Around Advice是环绕通知,是最常用的通知类型。前置通知和后置通知分别在目标类方法的前后织入通知,但是如果同时使用这两种类型的通知,使用环绕通知同样可以实现效果。
MethodInterceor
能够控制目标方法是否真的被调用。通过调用MethodInvocation.proceed()方法来调用目标方法。这一点不同于MethodBeforeAdvice,目标方法总是被调用,除非抛异常。
能够控制返回的对象,可以返回一个与MethodInvocation.proceed()方法返回的对象完全不同的对象。使用AfterReturningAdvice可以返回对象,但是不能返回一个不同的对象。相比,更加灵活。
package test.advice;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
public class GreetingAroundAdvice implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
// TODO Auto-generated method stub
Object args[] = invocation.getArguments();
String customName = (String) args[0];
System.out.println("欢迎:" + customName);
Object obj = invocation.proceed();
System.out.println("结束,再见:" + customName);
return obj;
}
}
<?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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<bean id="greetingBeforeAdvice"
class="test.advice.GreetingBeforeAdvice">
</bean>
<bean id="greetingAroundAdvice"
class="test.advice.GreetingAroundAdvice">
</bean>
<bean id="reception"
class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces"
value="test.advice.Reception"></property>
<property name="interceptorNames"
>
<list>
<!-- <value>greetingAfterAdvice</value>
<value>greetingBeforeAdvice</value> -->
<value>greetingAroundAdvice</value>
</list>
</property>
<property name="target" ref="target"></property>
</bean>
<bean id="target" class="test.advice.ConcreteReception"></bean>
<bean id="greetingAfterAdvice"
class="test.advice.GreetingAfterAdvice">
</bean>
</beans>
欢迎:Test我正在服务客户:Test
结束,再见:Test