Is it possible to unproxy a Spring bean?
Solution 1:
Try this:
if(AopUtils.isAopProxy(a) && a instanceof Advised) {
Object target = ((Advised)a).getTargetSource().getTarget();
AImpl ai = (AImpl)target;
}
Bonus: in Scala I am using the following equivalent function for the very same purpose:
def unwrapProxy(a: AnyRef) = a match {
case advised: Advised if(AopUtils.isAopProxy(advised)) =>
advised.getTargetSource.getTarget
case notProxy => notProxy
}
Solution 2:
With the introduction of Spring 4.2.RC1, there is now a dedicated utility class in the spring-test
module that handles this case for you.
The class is called AopTestUtils
and provides the methods:
-
getTargetObject
(unwraps only the top-level proxy) -
getUltimateTargetObject
(unwraps multiple levels of proxies if they exist).
Check out the relevant commit as well as the respective issue.