关于Spring动态代理
Posted sunbylm
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了关于Spring动态代理相关的知识,希望对你有一定的参考价值。
默认情况下,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动态代理的主要内容,如果未能解决你的问题,请参考以下文章