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?
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.
@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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With