码迷,mamicode.com
首页 > 编程语言 > 详细

关于Spring动态代理

时间:2017-05-16 23:32:03      阅读:259      评论:0      收藏:0      [点我收藏+]

标签:icp   ret   port   exce   sed   config   获取   cal   getc   

默认情况下,spring会按照如下规则生成代理:

当类有实现接口,spring会生成JdkDynamicAopProxy代理

当类没有实现接口,spring会生成CglibAopProxy代理

如果想强制spring生成CglibAopProxy代理,可以<aop:config proxy-target-class="true"> </aop:config>

当需要使用CGLIB代理和@AspectJ自动代理支持,请按照如下的方式设置 <aop:aspectj-autoproxy> 的 proxy-target-class 属性:<aop:aspectj-autoproxy proxy-target-class="true"/>

---------------------------------------------------------------------当通过JdkDynamicAopProxy实现代理的时候,如何获取到目标对象-------------------------------------------------------------

private static Object getJdkDynamicProxyTargetObject(Object proxy) throws Exception {
  Field h = proxy.getClass().getSuperclass().getDeclaredField("h");
  h.setAccessible(true);
  AopProxy aopProxy = (AopProxy) h.get(proxy);

  Field advised = aopProxy.getClass().getDeclaredField("advised");
  advised.setAccessible(true);

  Object target = ((AdvisedSupport) advised.get(aopProxy)).getTargetSource().getTarget();

  return target;
}

--------------------------------------------------------------------当通过CglibAopProxy实现代理的时候,如何获取目标对象---------------------------------------------------------------------------

private static Object getCglibProxyTargetObject(Object proxy) throws Exception {
Field h = proxy.getClass().getDeclaredField("CGLIB$CALLBACK_0");
h.setAccessible(true);
Object dynamicAdvisedInterceptor = h.get(proxy);

Field advised = dynamicAdvisedInterceptor.getClass().getDeclaredField("advised");
advised.setAccessible(true);

Object target = ((AdvisedSupport) advised.get(dynamicAdvisedInterceptor)).getTargetSource().getTarget();

return target;
}

 

关于Spring动态代理

标签:icp   ret   port   exce   sed   config   获取   cal   getc   

原文地址:http://www.cnblogs.com/man-li/p/6863775.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!