The BeanFactory provides an advanced configuration mechanism capable of managing beans (objects) of any nature, using potentially any kind of storage facility. The ApplicationContext builds on top of the BeanFactory (it's a subclass) and adds other functionality such as easier integration with Springs AOP features, message resource handling (for use in internationalization), event propagation, declarative mechanisms to create the ApplicationContext and optional parent contexts, and application-layer specific contexts such as the WebApplicationContext, among other enhancements.
In short, the BeanFactory provides the configuration framework and basic functionality, while the ApplicationContext adds enhanced capabilities to it, some of them perhaps more J2EE and enterprise-centric. In general, an ApplicationContext is a complete superset of a BeanFactory, and any description of BeanFactory capabilities and behavior should be considered to apply to ApplicationContexts as well.
Users are sometimes unsure whether a BeanFactory or an ApplicationContext are best suited for use in a particular situation. Normally when building most applications in a J2EE-environment, the best option is to use the ApplicationContext, since it offers all the features of the BeanFactory and adds on to it in terms of features, while also allowing a more declarative approach to use of some functionality, which is generally desirable. The main usage scenario when you might prefer to use the BeanFactory is when memory usage is the greatest concern (such as in an applet where every last kilobyte counts), and you don't need all the features of the ApplicationContext.
Initializing the Application Context
Before using the application context we need to instantiate it via the
org.springframework.context.support.FileSystemXmlApplicationContext class from the Spring framework. This is an expensive process that involves to open and parse theapplicationContext.xml file.This expensive operation is the reason why I created the factory method and made is as a Singleton.
private ApplicationContext context; private static final String APPLICATION_CONTEXT_FILE = "applicationContext.xml"; private BatBotResourceFactory() { context = new FileSystemXmlApplicationContext(APPLICATION_CONTEXT_FILE); }
obtaining the Beans
Once the
org.springframework.context.ApplicationContext is created and saved in thecontext field. it can be used to retrieve the beans from the Spring framework. At this point it's very simple:All you need to do is to call the
getBean MethodObject org.springframework.beans.factory.BeanFactory.getBean(String name) throws BeansException
Posted in: