有没有办法检查是否在spring上下文中定义了bean?

时间:2015-08-03 10:04:28

标签: java spring

我正在尝试创建一个对象工厂,它将首先检查bean是否已在spring上下文中专门定义。如果找不到这样的bean,它将检查创建实例的其他方法。

我使用以下代码实现了它

try {
        component = (PageComponent) appContext.getBean(w.getName());
    } catch (org.springframework.beans.factory.NoSuchBeanDefinitionException e) {
            component = loadFromDB(w, page);
    }

它正在工作,但是只要bean在Spring Context中不可用,就会创建一个异常对象。

有没有办法避免这种情况?或者换句话说,有没有办法检查bean是否在spring上下文中定义?

3 个答案:

答案 0 :(得分:8)

试试这个:

if(appContext.containsBeanDefinition(w.getName()))
    ; // Get the bean

答案 1 :(得分:0)

beanFactory.containsBean(w.getName())将返回boolean值,具体取决于是否已经通过此名称注册了bean。看看here

做这样的事情

if (!((BeanFactory) applicationContext).containsBean(w.getName())) {
     component = loadFromDB(w, page);
}

答案 2 :(得分:0)

您也可以使用ApplicationContextRunner

假设我有一个以某些config-prop为条件的bean。

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
  }