I am trying to create an object factory, which will first check if a bean has been specifically define in spring context. If such a bean is not found, It would check for other ways to create the instance.
I have implemented it using the following code
try {
component = (PageComponent) appContext.getBean(w.getName());
} catch (org.springframework.beans.factory.NoSuchBeanDefinitionException e) {
component = loadFromDB(w, page);
}
It is working, however an exception object is created whenever the bean is not available in Spring Context.
Is there a way to avoid this? or in other words Is there a way to check if a bean is defined in spring context?
Here's a definition of beans in the Spring Framework documentation: In Spring, the objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container.
Beans from parent context are visible in child context but not vice-versa. That way, a child context can use beans and configuration from parent context and override only what's necessary. Example of that can be a security defined in parent context and used/overridden in child contexts.
In Spring Boot, you can use appContext. getBeanDefinitionNames() to get all the beans loaded by the Spring container.
The ApplicationContext comes with advanced features, including several that are geared towards enterprise applications, while the BeanFactory comes with only basic features. Therefore, it's generally recommended to use the ApplicationContext, and we should use BeanFactory only when memory consumption is critical.
Try this:
if(appContext.containsBeanDefinition(w.getName()))
; // Get the bean
beanFactory.containsBean(w.getName())
will return a boolean
value depending on if there's already a bean registered by this name. Take a look at here.
Do something like this
if (!((BeanFactory) applicationContext).containsBean(w.getName())) {
component = loadFromDB(w, page);
}
You can also use ApplicationContextRunner
Suppose I have a bean that conditional on some config-prop.
class IsExistBeanTest {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withUserConfiguration(SomeConfig.class)
@Test
void TestIfBeanIsThereWhenPropsExist() {
contextRunner
.withPropertyValues("some-left-service=false")
.run(context -> assertAll(
() -> assertThat(context).hasSingleBean(SomeBean.class),
() -> assertThat(context).doesNotHaveBean(SomeOtherBean.class)));
() -> assertThat(context).hasBean(SomeBean2.class)));
//() -> more test case
}
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