2018-1 Spring AOP - 2

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"/>





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值