Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I understand whether a bean exists in 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 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?

like image 505
Mary Ryllo Avatar asked Feb 06 '13 07:02

Mary Ryllo


People also ask

Can we create a bean at runtime?

This can be done without restarting the application at runtime when Loading and Removing bean in Spring Application. If the client code needs to register objects which are not managed by Spring container, then we will need to work with an instance of BeanDefinition. Here, We have used the following dependencies.

What does @bean annotation mean?

@Bean is a method-level annotation and a direct analog of the XML <bean/> element. The annotation supports most of the attributes offered by <bean/> , such as: init-method , destroy-method , autowiring , lazy-init , dependency-check , depends-on and scope .

What does @bean on a method mean?

Spring @Bean Annotation is applied on a method to specify that it returns a bean to be managed by Spring context. Spring Bean annotation is usually declared in Configuration classes methods. In this case, bean methods may reference other @Bean methods in the same class by calling them directly.


1 Answers

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.

like image 118
Aaron Digulla Avatar answered Oct 07 '22 19:10

Aaron Digulla