是否可以取消代理 Spring bean? [英] Is it possible to unproxy a Spring bean?

查看:52
本文介绍了是否可以取消代理 Spring bean?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Spring bean,比方说:

I have a Spring bean, let's say:

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

     public void setSomeDependency(D dependency) {
         // This setter DOES NOT BELONG to interface A
     }
}

<bean id="aImpl" class="AImpl"/>

现在我想对其进行集成测试,但首先我需要模拟依赖项 D,因为它做了太多的事情.由于AImpl实现了一个接口并且包含了一个事务注解,所以生成的代理只兼容A接口,所以我可以这样做:

Now I want to integration test it, but first I need to mock the dependency D, because it does too much stuff. Since the AImpl implements an interface and contains a transactional annotation, the generated proxy is only compatible with the interface A, so I can do this:

@Inject @Named("aImpl")
private A a;

但不能:

@Inject @Named("aImpl")
private AImpl a;

因此,我无法嘲笑我的依赖.

As a result, I can't mock my dependency.

请注意,将void setSomeDependency(D dependency) 添加到接口A 不是一种选择,因为它没有商业意义.它也没有使用 proxy-target-class="true",因为它破坏了很多其他 bean(此属性影响上下文中的所有 bean).

Please note that adding void setSomeDependency(D dependency) to interface A is not an option, as it has no business meaning. Neither it is using the proxy-target-class="true", as it breaks a whole lot of other beans (this attribute affects all beans in the context).

有没有办法取消代理注入的 bean A,这样我就可以将它转换为 AImpl?

Is there a way to unproxy the injected bean A, so I could cast it to AImpl?

推荐答案

试试这个:

if(AopUtils.isAopProxy(a) && a instanceof Advised) {
    Object target = ((Advised)a).getTargetSource().getTarget();
    AImpl ai = (AImpl)target;
}

奖励:在 Scala 中,我出于相同的目的使用以下等效函数:

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
}

这篇关于是否可以取消代理 Spring bean?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆