How to use DefaultListableBeanFactory in Spring?
In Spring, DefaultListableBeanFactory is a default implementation of the BeanFactory interface, offering a flexible way to implement a BeanFactory. It allows for registering Bean definitions through reading configuration files or programmatically, and manages dependencies between Beans.
These are the steps to use DefaultListableBeanFactory:
- Instantiate a DefaultListableBeanFactory object.
- Create a DefaultListableBeanFactory named beanFactory.
- Bean definitions can be registered programmatically or through reading configuration files.
- a. Bean definitions can be registered programmatically.
- Create a new instance of GenericBeanDefinition and assign it to the variable beanDefinition. Set the bean class to YourBeanClass and register the bean definition with the name “yourBeanName” in the beanFactory.
- b. Reading configuration files to register Bean definitions:
- Create a new XmlBeanDefinitionReader object, passing in a beanFactory, and then load bean definitions from a file named “your-config.xml” within the specified classpath.
- Obtain Bean instances:
You can obtain Bean instances by using the getBean method of the beanFactory, by providing the name or type of the Bean. - Create an instance of YourBeanClass using the beanFactory with the name “yourBeanName”.
- Use the Bean instance:
- Perform an action on the bean.
Please note:
- When registering Bean definitions, it is necessary to specify the name of the Bean and its corresponding BeanDefinition, with the Bean name being unique within the container.
- When obtaining a Bean instance through the getBean method, if the type of the Bean is not unique, you can specify it either by its name or by its type.
I hope this helps you!