AfterAdvice即后置通知,与前置通知用法相似,但是功能是想反的,后置通知是指在目标方法被调用后执行。
实现后置通知必须实现AfterReturningAdvice接口,同前置通知一样,后置通知有机会得到调用的方法、传入的参数以及目标对象,亦可以获得被通知方法的返回值。这个接口返回的也是空值。虽然可以获得目标方法的返回值,但是不能替换返回值。与前置通知相同,改变执行流程的唯一方法就是抛出异常。
package test.advice;
import java.lang.reflect.Method;
import org.springframework.aop.AfterReturningAdvice;
public class GreetingAfterAdvice implements AfterReturningAdvice {
@Override
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
// TODO Auto-generated method stub
String customName = (String) args[0];
System.out.println(customName + ": 结束服务");
}
}
<?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="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>
</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>
public static void main(String[] args) {
// Reception target = new ConcreteReception();
// BeforeAdvice advice = new GreetingBeforeAdvice();
// ProxyFactory pf = new ProxyFactory();
// pf.setTarget(target);
// pf.addAdvice(advice);
// Reception proxy = (Reception) pf.getProxy();
// proxy.serveCustomer("HeMaSoft.com");
ApplicationContext context = new ClassPathXmlApplicationContext("spring-servlet.xml");
Reception reception = (Reception) context.getBean("reception");
reception.serveCustomer("Test");
}
}
欢迎:Test ,很高兴为您服务我正在服务客户:Test
Test: 结束服务