9

For example, I have a class

public class Car{
     private Motor motor;

     public void setMotor(Motor motor){
          this.motor = motor;
     }   
}

My bean looks like

<bean id="car" class="Car">
    <property name="motor" ref="${motorProvider.getAvailableMotor()}"/>
</bean>

This method: motorProvider.getAvailableMotor() returns a bean name(string), of which motor I should use.

But there can be a situation when such bean(with such name) is not created. How can I check it?

bluesman80
  • 154
  • 3
  • 13
Mary Ryllo
  • 2,321
  • 7
  • 34
  • 53

2 Answers2

23

There are several patterns how to do this. Here is one I often use:

public class Car{
     private Motor motor;

     @Autowired
     private ApplicationContext applicationContext;

     @PostConstruct
     public void init() {
        try {
            motor = applicationContext.getBean( Motor.class );
        } catch( NoSuchBeanDefinitionException e ) {
            motor = new DefaultMotor();
        }
     }
}

Note you could also call applicationContext.containsBeanDefinition(name) but that would search your context twice (once in containsBeanDefinition() and then second time when you call getBean()) so catching the exception is usually faster.

Since we catch a specific exception that says "bean doesn't exist", using if/else has almost no advantage anymore.

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
3

SPeL; something like:

<property name="motor" value="#(if(${motorProvider} != null) ${motorProvider.getAvailableMotor()})"/>

I think it was discussed also here: Spring - set a property only if the value is not null . As they said before for more information see: http://static.springsource.org/spring/docs/3.0.5.RELEASE/reference/expressions.html

Community
  • 1
  • 1
Liviu Stirb
  • 5,876
  • 3
  • 35
  • 40
  • 1
    I think, you don't don't understand me right) I don't want to check something on null, I want to understand is there such bean in my context. Because if such bean is not created, spring will cause an exception – Mary Ryllo Feb 06 '13 at 07:54