默认情况下,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;
}
摘自:
http://www.cnblogs.com/yangyquin/p/5582911.html