且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在bean存在时注入它

更新时间:2023-10-06 14:13:22

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;
    }
}