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 classpublic 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 Advicepublic 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);
}
}usingimport 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"/>

本文详细介绍了 Spring AOP 的五种增强机制,包括前置、后置、环绕、异常及引介增强,并通过具体示例展示了如何实现前置增强。

被折叠的 条评论
为什么被折叠?



