是否有可能解除Spring bean的问题? [英] Is it possible to unproxy a Spring bean?

查看:107
本文介绍了是否有可能解除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天全站免登陆