`
wanxiaotao12
  • 浏览: 461372 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

spring aop、JDK代理实现机制

 
阅读更多

AOP的实现机制

 

生成的动态代理类:

1、将Invocationhandler的实现类作为代理类的成员变量

<!--EndFragment-->
2、代理方法, 先获取目标方法,然后执行InvocationHandler实现的invoke方法
 
public class ProxyBusiness implements IBusiness, IBusiness2 { 
//将Invocationhandler的实现类作为代理类的成员变量
private LogInvocationHandler h; 

@Override 
public void doSomeThing2() { 
    try { 
        Method m = (h.target).getClass().getMethod("doSomeThing", null); 
        h.invoke(this, m, null); 
    } catch (Throwable e) { 
        // 异常处理(略) 
    } 
} 

@Override 
public boolean doSomeThing() { 
    try {
       //取得目标对象的方法,然后将methoed对象传到invocationHandler.invoke()方法
       Method m = (h.target).getClass().getMethod("doSomeThing2", null);
       //在invoke的方法中,可以在目标方法前增加, 也可以目标方法后增加 
       return (Boolean) h.invoke(this, m, null); 
    } catch (Throwable e) { 
        // 异常处理(略) 
    } 
    return false; 
} 

public ProxyBusiness(LogInvocationHandler h) { 
    this.h = h; 
} 

//测试用 
public static void main(String[] args) { 
    //构建AOP的Advice 
    LogInvocationHandler handler = new LogInvocationHandler(new Business()); 
    new ProxyBusiness(handler).doSomeThing(); 
    new ProxyBusiness(handler).doSomeThing2(); 
} 
} 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics