Search This Blog

Tuesday, 1 May 2012

Using the ApplicationContext

In all of the previous posts we have been working with the BeanFactory. However in order to use all of Spring's functionalities we need to use a more powerful version of the Spring Container.
The ApplicationContext is a type of the BeanFactory but a much more powerful version. Along with the basic bean factory behaviour it also provides :
  1. Ability to load file resources in a generic fashion.
  2. Ability to publish events to registered listeners.
  3. Ability to resolve properties.
  4. Support for internationalization.
I decided to create a simple bean and have it loaded from the application context.
public class HelloWorldMessanger {

    public String getMessage() {
        return "Hello World";
    }
}
The code to test the same is:
public class Client {

    public static void main(String[] args) throws FileNotFoundException {
        final ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
                "beans.xml");
        HelloWorldMessanger messager = (HelloWorldMessanger) applicationContext
                .getBean("messager");
        System.out.println(messager.getMessage());
    }
}
Unlike the bean factory, the code requires several more jars.
Jars needed for using ApplicationContext
On executing the above test code:
Feb 23, 2012 8:46:26 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@be2358: startup date 
[Thu Feb 23 20:46:26 IST 2012]; root of context hierarchy
Feb 23, 2012 8:46:26 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [beans.xml]
Feb 23, 2012 8:46:27 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@af8358:
 defining beans [messager]; root of factory hierarchy
Hello World

No comments:

Post a Comment