Application Context Aware
Spring Inversion of Control (IoC ) also known as
Dependency Injection (DI ) is a process by which
objects define their dependencies with collaborating objects.
Spring provides ApplicationContextAware interface which allows us to have access to the
ApplicationContext that created the bean implementing this interface.
ApplicationContextAware.java
package org.springframework.context;
import org.springframework.beans.BeansException;
public abstract interface ApplicationContextAware
{
public abstract void setApplicationContext(ApplicationContext paramApplicationContext)
throws BeansException;
}
package com.bethecoder.tutorials.spring3.basic;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class SimpleBeanFactory implements ApplicationContextAware {
private ApplicationContext applicationContext = null ;
private int count = 0 ;
@Override
public void setApplicationContext ( ApplicationContext applicationContext )
throws BeansException {
System.out.println ( "Injecting ApplicationContext" ) ;
this .applicationContext = applicationContext;
}
public SimpleBean getSimpleBean () {
SimpleBean simpleBean = ( SimpleBean ) applicationContext.getBean ( "template" ) ;
simpleBean.setSimpleProp ( "ABC" + ++count ) ;
return simpleBean;
}
}
package com.bethecoder.tutorials.spring3.basic;
public class SimpleBean {
private String simpleProp;
public String getSimpleProp () {
return simpleProp;
}
public void setSimpleProp ( String simpleProp ) {
this .simpleProp = simpleProp;
}
}
package com.bethecoder.tutorials.spring3.tests.aware;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.bethecoder.tutorials.spring3.basic.SimpleBean;
import com.bethecoder.tutorials.spring3.basic.SimpleBeanFactory;
public class ApplicationContextAwareTest {
/**
* @param args
*/
public static void main ( String [] args ) {
System.out.println ( "Initializing ApplicationContext" ) ;
ApplicationContext factory = new ClassPathXmlApplicationContext ( "app_context.xml" ) ;
System.out.println ( "ApplicationContext Initialized" ) ;
SimpleBeanFactory simpleFactory = ( SimpleBeanFactory ) factory.getBean ( "simpleFactory" ) ;
SimpleBean simple = simpleFactory.getSimpleBean () ;
System.out.println ( simple + "->" + simple.getSimpleProp ()) ;
simple = simpleFactory.getSimpleBean () ;
System.out.println ( simple + "->" + simple.getSimpleProp ()) ;
simple = simpleFactory.getSimpleBean () ;
System.out.println ( simple + "->" + simple.getSimpleProp ()) ;
}
}
It gives the following output,
Initializing ApplicationContext
Injecting ApplicationContext
ApplicationContext Initialized
com.bethecoder.tutorials.spring3.basic.SimpleBean@97d01f->ABC1
com.bethecoder.tutorials.spring3.basic.SimpleBean@e0a386->ABC2
com.bethecoder.tutorials.spring3.basic.SimpleBean@feb48->ABC3