Wednesday, November 25, 2009

Getting the proxied object from a dynamic spring proxy

In a project I am currently working on, we are using Spring-AOP. Spring's AOP implementation 'transparently' proxies objects to facilitate its AOP implementation. You have the choice of CGLIB proxies (class based proxying) or JDK Dynamic Proxies (interface base proxying). Either one is fine... but there came a time when my proxied object didn't quite behave like the object it was proxying. I was trying to get a hibernate DataSource object from a SessionFactory using this code:

DataSource ds = SessionFactoryUtils.getDataSource(sf);

Unforunately, because my SessionFactory is a proxy object, this code was returning null... still not sure why. I knew it worked with the 'un-proxied' SessionFactory, so needed to get access to it. If you are ever in this bind, here is a snippit that will work:

public T getTargetObject(Object proxy, Class targetClass) throws Exception {
if (AopUtils.isJdkDynamicProxy(proxy) && proxy instanceof Advised) {
return (T) ((Advised)proxy).getTargetSource().getTarget();
} else {
return (T) proxy;
}
}

Hope this helps! Any comments, please post'em.

Cheers,

Yeuker

No comments:

Post a Comment