BeanFactory
BeanFactory is an implementation of the factory pattern that applies IOC to separate application’s configuration & dependencies from the actual application code.
The BeanFactory is the actual container which instantiates, configures, and manages the beans. These beans typically collaborate with one another, and thus have dependencies between themselves. These dependencies are reflected in the configuration data used by the BeanFactory.
A BeanFactory is represented by the interface org.springframework.beans.factory.BeanFactory for which there are multiple implementations.
Resource res = new FileSystemResource("beans.xml");
XmlBeanFactory factory = new XmlBeanFactory(res);
- OR -
ClassPathResource res = new ClassPathResource("beans.xml");
XmlBeanFactory factory = new XmlBeanFactory(res);
- OR -
ClassPathXmlApplicationContext appContext =
new ClassPathXmlApplicationContext( new String[]
{ "applicationContext.xml", "applicationContext-part2.xml"} );
// Of course, an ApplicationContext is just a BeanFactory
BeanFactory factory = (BeanFactory) appContext;
XMLBeanFactory
XMLBeanFactory is a bean factory that is loaded its beans from an XML file.
BeanFactory has many implementations in Spring but one of the most useful one is org.springframework.beans.factory.xml.XmlBeanFactory, which loads its beans based on the definitions contained in an XML file.
To create an XmlBeanFactory, pass a java.io.InputStream to the constructor. The InputStream will provide the XML to the factory.
For example, the following code snippet uses a java.io.FileInputStream to provide a bean definition XML file to XmlBeanFactory.
BeanFactory factory =
new XmlBeanFactory(new FileInputStream("beans.xml"));
To retrieve the bean from a BeanFactory
Call the getBean() method by passing the name of the bean you want to retrieve.
MyBean myBean = (MyBean) factory.getBean("myBean");
No comments:
Post a Comment
Note: only a member of this blog may post a comment.