lefed

Accessing Proxy Targets in Spring

30 Oct 2013 / posted by Nikku

In a recent dive into spring framework proxies I was searching for a way to access real objects behind a proxy. That was required to fix field injection in jerseys jersey-spring3 extension.

It turns out that this is easily possible through the Advised interface that gets added to spring bean proxies as a management interface.

The interface provides the method getTargetSource()) that allows you to access the current proxy target source.

if (bean instanceof Advised) {
  Object realTarget = ((Advised) bean).getTargetSource().getTarget();

  inject(realTarget);
}

The above code does work for static proxy targets, only. It breaks if hot swapping or pooling is used because the target obtained may be different on each access.

Your application code should not use those internal interfaces, anyway. Your libraries may.

Tagged as [ spring, java ]