public
Created

access target behind spring proxy

  • Download Gist
gistfile1.java
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
// 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);
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.