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?
There are several patterns how to do this. Here is one I often use:
Note you could also call
applicationContext.containsBeanDefinition(name)but that would search your context twice (once incontainsBeanDefinition()and then second time when you callgetBean()) so catching the exception is usually faster.Since we catch a specific exception that says “bean doesn’t exist”, using
if/elsehas almost no advantage anymore.