Skip to content

Instantly share code, notes, and snippets.

@langmi
Created January 9, 2012 09:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save langmi/1582202 to your computer and use it in GitHub Desktop.
Save langmi/1582202 to your computer and use it in GitHub Desktop.
access target behind spring proxy
// from http://www.techper.net/2009/06/05/how-to-acess-target-object-behind-a-spring-proxy/
@SuppressWarnings({"unchecked"})
protected <T> T getTargetObject(Object proxy, Class<T> targetClass) throws Exception {
if (AopUtils.isJdkDynamicProxy(proxy)) {
return (T) ((Advised)proxy).getTargetSource().getTarget();
} else {
return (T) proxy; // expected to be cglib proxy then, which is simply a specialized class
}
}
// alternative for a proxied MultiResourceItemReader, beware works only if you configure StepScope with
// <bean class="org.springframework.batch.core.scope.StepScope" p:proxyTargetClass="true" />
if (proxy instanceof Advised) {
try {
Advised advised = (Advised) proxy;
Object obj = advised.getTargetSource().getTarget();
MultiResourceItemReader mrirTarget = (MultiResourceItemReader) obj;
// ... usage
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
@NemchinovSergey
Copy link

Object target = AopProxyUtils.getSingletonTarget(proxy);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment