This is a series and it would make a lot of sense if read in a sequence. You can find all the posts under the heading “Spring Beginners to Professionals“. In the previous post we mentioned about the BeanFactory. Here we will try and put some more effort in understanding the BeanFactory. A deeper understanding of the BeanFactory will ease our journey further.
Understanding the BeanFactory
As our XML configuration metadata is a container of bean elements, so is our BeanFactory a container of BeanDefinitions and in turn beans. We can consider the BeanFactory as a central registry which centralizes configuration of application components.
The bean factory is responsible for loading the bean definitions from the bean metadata stored in a configuration file. It is responsible for returning a bean instance given a bean name, it can also return a list of bean instances given a Type. It is also responsible for answering basic question about a given bean like
- Is the bean contained in the factory?
- What are the aliases of the bean?
- Type of the bean?
- Scope of the bean?
Bean Factory is often termed as the IoC container because they act as a holder of the beans and help in wiring collaborating beans. Spring offers different sub interfaces of the BeanFactory interface for different needs. The most important ones are the ListableBeanFactory and HierarchicalBeanFactory.
The ListableBeanFactory enumerates all the beans in the factory. This is of great help when you want to get all the beans in the application at once. When you do not need to query the beans one by one based on their names. The bean factories which prefer pre-loading of all the bean definitions generally implement this interface. For e.g. the XML based factories.
It only lists the beans defined in the this factory, which can be considered as a drawback. If this factory lies in any hierarchy, it won’t return the beans in the hierarchy in the list of beans returned as a result of invocation of getBeanDefinitionNames() or getBeanDefinitionCount()
The HeirarchicalBeanFactory supports hierarchy of bean factories. While creating such a bean factory, you can supply a parent bean factory.