Search This Blog

Sunday 13 May 2012

The ApplicationContextAware Interface

In the previous post we saw how the ApplicationContext as the more powerful container in Spring. In a BeanFactory based environment Spring provides us with the BeanFactoryAware interface to help a bean get access to its loading BeanFactory container.Similarly for the application context
we have the ApplicationContextAware interface.
public class SimpleCar implements ICar, ApplicationContextAware {

    @Override
    public String describe() {
        return "Car is an empty car";
    }

    @Override
    public void setApplicationContext(ApplicationContext appContext)
            throws BeansException {
        System.out.println("received the app context " + appContext);
    }

}
The bean definition for the same is as below:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd" >

    <bean id ="bustedCar" class="com.start.SimpleCar"/>
</beans>
On testing the code:
public static void main(String[] args) throws FileNotFoundException {
    final ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
            "beans.xml");
    SimpleCar car = (SimpleCar) applicationContext.getBean("bustedCar");
    System.out.println(car.describe());
}
The output indicates that the bean was assigned with the ApplicationContext:
May 12, 2012 11:56:49 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1027b4d: startup date 
[Sat May 12 23:56:49 IST 2012]; root of context hierarchy
May 12, 2012 11:56:50 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [beans.xml]
May 12, 2012 11:56:51 PM org.springframework.beans.factory.support.DefaultListableBeanFactory 
preInstantiateSingletons INFO: Pre-instantiating singletons in org.springframework.beans.factory.
support.DefaultListableBeanFactory@d80be3:
 defining beans [messager,bustedCar]; root of factory hierarchy
received the app context org.springframework.context.support.ClassPathXmlApplicationContext@1027b4d:
 startup date [Sat May 12 23:56:49 IST 2012]; root of context hierarchy
Car is an empty car

No comments:

Post a Comment