Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to check if a bean is defined in spring context?

Tags:

java

spring

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?

like image 997
Mohit Kanwar Avatar asked Aug 03 '15 10:08

Mohit Kanwar


People also ask

How Spring define bean in 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.

Are beans defined in parent context visible to child contexts?

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.

How do I know if beans are initialized in Spring boot?

In Spring Boot, you can use appContext. getBeanDefinitionNames() to get all the beans loaded by the Spring container.

Can you compare bean factory with application context?

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.


3 Answers

Try this:

if(appContext.containsBeanDefinition(w.getName()))
    ; // Get the bean
like image 137
Kayaman Avatar answered Sep 20 '22 21:09

Kayaman


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);
}
like image 42
mushfek0001 Avatar answered Sep 23 '22 21:09

mushfek0001


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
  }
like image 43
z atef Avatar answered Sep 20 '22 21:09

z atef