How to inject a bean only when it exists

前端 未结 2 486
醉梦人生
醉梦人生 2021-01-05 11:28

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

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


        
相关标签:
2条回答
  • 2021-01-05 12:31

    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.

    0 讨论(0)
  • 2021-01-05 12:34

    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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题