如何在bean存在时注入它 [英] How to inject a bean only when it exists

查看:148
本文介绍了如何在bean存在时注入它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有弹簧上下文文件的以下结构( - > 代表'includes'):

I have the following structure of spring context files ( -> stands for 'includes') :

A1.xml -> B.xml & C.xml
A2.xml -> B.xml

C.xml 定义一个bean c

C.xml defines a bean c

B.xml 定义一个bean b 依赖于 c

B.xml defines a bean b with a dependency on c

显然这是失败的A2,因为上下文 A2 中没有定义 c

Obviously this fails for A2, because there is no c defined in the context A2.

如何指定类似的内容:如果您在上下文中有 c ,请将其注入 b 否则只需注入 null

How can I specify something like: if you have c in the context inject it in b otherwise just inject null?

我查看了Spring EL但是

I looked into Spring EL but

<property name="b" ref="#{ @c?:null}" />

刚给了我一个名字的 NoSuchBeanDefinitionException 这似乎是的价值b.toString()!?

Just gave me a NoSuchBeanDefinitionException for a name which seemed to be the value of b.toString() !?

Btw:我已经知道这件事很糟糕,应尽快清理。

Btw: I already know that this thing is messy as hell and should be cleaned up as fast as possible.

推荐答案

SpEL表达式的#root对象是BeanExpressionContext ,您可以在该上下文中调用 getObject()方法;如果没有声明bean,它返回null ...

The #root object of the SpEL Expression is a BeanExpressionContext, you can invoke the getObject() method on that context; it returns null if the bean is not declared...

<property name="bar" value="#{getObject('bar')}" />

注意:您使用而不是 ref 因为它返回bean而不是bean定义。

Note: you use value not ref because it returns the bean, not the bean definition.

这是来自 getObject的代码( )

public Object getObject(String key) {
    if (this.beanFactory.containsBean(key)) {
        return this.beanFactory.getBean(key);
    }
    else if (this.scope != null){
        return this.scope.resolveContextualObject(key);
    }
    else {
        return null;
    }
}

这篇关于如何在bean存在时注入它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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