How to inject a bean only when it exists

旧巷老猫 提交于 2019-11-30 20:21:15

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')}" />

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

Here's the code from 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;
    }
}
Anders R. Bystrup

I quite agree with cleaning up your XML :-)

If you're using annotation based injection, you might try this trick

@Autowired( required=false )

I'm unsure whether this will work in your situation, but it's worth a try.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!