Sping增强
包含:
1. 前置增强: org.springframework.aop.BeforeAdvice
2. 后置增强: org.springframework.aop.AfterReturningAdvice
3.环绕增强: org.aopallicance.intercept.MethodInterceptor, 在方法前后执行
4. 异常抛出增强: org.springframework.aop.ThrowsAdvice
5. 引介增强: org.springframework.aop.IntrodutionInterceptor
BeforeAdvice example
The NaiveWaiter as the target class
public class NaiveWaiter implements Waiter{
public void greetTo(String name){
System.out.println("greet to"+name);
}
public void serveTo(String name){
System.out.println("serving"+name);
}
}
The Advice
public class GreetingBeforeAdvice implements MethodBeforeAdvice{
public void before(Method method, Object[] args, Object o) throws Throwable{
String clientName = (String)args[0];
System.out.println("how are you! " + clientName);
}
}
using
import org.springframework,aop.framework.ProxyFactory;
public class TestBeforeAdvice{
public static void main(String[] args){
Waiter target = new NaiveWaiter();
BeforeAdvice advice = new GreetingBeforeAdvice();
ProxyFactory pf = new ProxyFactory();
pf.setTarget(target);
pf.addAdvice(advice);
Waiter proxy = (Waiter)pf.getProxy();
proxy.greeTo("John");
proxy.serveTo("Tom");
}
}
<bean id="greetingAdvice" class="GreetingBeforeAdvice"/>
<bean id="target" class="NaiveWaiter"/>
<bean id="waiter" class ="org.springframework.aop.framework.ProxyFactoryBean"
p:proxyInterfaces="Waiter"
p:interceptorNames="greetingAdvice"
p:target-ref="target"/>