Is there a way to check if a bean exists in the context of spring?

I am trying to create a factory object that first checks to see if a bean has been defined in a specific way in the spring context. If such a bean is not found, it will check other ways to create the instance.

I 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 works, however an exception object is created whenever a bean is not available in the spring Context.

Is there any way to avoid this? or, in other words, is there a way to check if a bean exists in the context of spring?

+5
source share
2 answers

Try the following:

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

beanFactory.containsBean(w.getName()) will return boolean depending on whether a bean already registered with this name exists. Take a look here .

Do something like this

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

All Articles