Is it possible to unproxy a Spring bean?

前端 未结 2 1678
时光取名叫无心
时光取名叫无心 2020-12-01 13:58

I have a Spring bean, let\'s say:

@TransactionAttribute(TransactionAttributeType.REQUIRED) 
public class AImpl implements A {

     public void setSomeDepend         


        
相关标签:
2条回答
  • 2020-12-01 14:45

    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
    }
    
    0 讨论(0)
  • 2020-12-01 14:46

    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.

    0 讨论(0)
提交回复
热议问题