How can I figure out if a bean exists at runtime?

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 the name of the bean (string) from which I should use the engine.

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

+3


source to share


2 answers


There are several templates for how to do this. Here's what I use a lot:

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 that you can call as well applicationContext.containsBeanDefinition(name)

, but this will search your context twice (once in containsBeanDefinition()

and then the second time when you call getBean()

), so that traversing the exception is usually faster.

Since we will catch a specific exception that says "bean does not exist", using if

/ else

no longer has any benefit.

+9


source


Spel; something like:

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

      



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

+2


source







All Articles