9

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

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

C.xml defines a bean c

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

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

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

I looked into Spring EL but

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

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

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

Gary Russell
  • 166,535
  • 14
  • 146
  • 179
Jens Schauder
  • 77,657
  • 34
  • 181
  • 348

2 Answers2

23

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;
    }
}
Gary Russell
  • 166,535
  • 14
  • 146
  • 179
10

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.

Alexander Farber
  • 21,519
  • 75
  • 241
  • 416
Anders R. Bystrup
  • 15,729
  • 10
  • 59
  • 55