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 {

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

    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=""
    xsi:schemaLocation="" >

    <bean id ="bustedCar" class="com.start.SimpleCar"/>
On testing the code:
public static void main(String[] args) throws FileNotFoundException {
    final ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
    SimpleCar car = (SimpleCar) applicationContext.getBean("bustedCar");
The output indicates that the bean was assigned with the ApplicationContext:
May 12, 2012 11:56:49 PM prepareRefresh
INFO: Refreshing 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 
preInstantiateSingletons INFO: Pre-instantiating singletons in org.springframework.beans.factory.
 defining beans [messager,bustedCar]; root of factory hierarchy
received the app context
 startup date [Sat May 12 23:56:49 IST 2012]; root of context hierarchy
Car is an empty car

No comments:

Post a Comment