Looking at Spring's Bean Factories
by, 11-15-2011 at 03:17 PM (927 Views)
BeanFactory serves as the core to Spring's Dependency Injection implementation. A BeanFactory is responsible for managing components and their dependencies. Bean is the term used in Spring to refer to any component managed by the container. Typically all Spring beans adhere, at some level, to the JavaBeans specification, although it is not required. The most obvious case of Spring deviating from the JavaBean specification is with the use of Constructor Injection to wire your beans together.
The BeanFactory is what your application uses in order to interact with Spring Dependency Injection container. In order to access beans via the BeanFactory, you must your application must create an instance of a class that implements the BeanFactory interface and then configure it with bean and dependency information. This normally takes place at startup. In general, Spring will do most of this for you as long as you configure the appropriate class with the BeanFactory interface to startup at runtime and you have configured the Spring xml file or the class with appropriate annotations.
The most commonly used route to configure a BeanFactory is to use an external xml configuration file. Note that this can also be done programmatically. Internally, bean configuration is represented by instances of classes that implement the BeanDefinition interface. The bean configuration stores information about a bean itself, as well as the beans that it depends on. Any BeanFactory class that implements the BeanDefinitionRegistry interface reads the BeanDefinition data from a configuration file using either XmlBeanDefinitionReader or PropertiesBeanDefinitionReader. The two main BeanFactory implementations that come with Spring implement BeanDefinitionRegistry. Below is an example of how to create an XMLBeanFactory:
Now once instantiated you can use it to retrieve any bean that has been configured by calling the getBean() method.Java Code:BeanFactory factory = new XmlBeanFactory(new FileInputStream("beans.xml"));
When getBean() is called, the factory will instantiate the bean and begin setting the beanís properties using dependency injection.Java Code:MyBean myBean = (MyBean) factory.getBean("myBean");