“Aware” in Spring

The name is just a convention on Spring meaning that some special framework object is going to be injected to that class if it is managed by the framework.

Directly from the docs of ApplicationContextAware:

Interface to be implemented by any object that wishes to be notified of the ApplicationContext that it runs in.

In this case, the bean that implements this interface will get a reference to the ApplicationContext managing the application.


BeanNameAware means right after instantiation and properties are set, Spring will call back to your bean and give it the id that it has been given.

BeanNameAware has

setBeanName(String name) as its interface method. You can hold onto the value as an instance variable and make your toString print out a nice message.

ApplicationContextAware interface has setApplicationContext(ApplicationContext context) as its method that gets called and the ApplicationContext is passed in to it, if you needed to say call getBean somewhere in that class at anytime.

Typically, you do not implement any of these interfaces as it will couple your code to Spring. And Spring doesn’t want you to do that anyway. But it is a hook to the Spring Initialization phase.



Consider the two interfaces BeanNameAware and BeanFactoryAware. The first one makes the object aware of their bean name in a bean factory. The second interface gives the bean access to the Bean Factory that created it.
Consider the below class:

public class SimpleCar implements ICar, BeanNameAware, BeanFactoryAware {

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

    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        System.out.println("received the beanFactory " + beanFactory);


    public void setBeanName(String name) {
        System.out.println("the name of the bean is " + name);


I created a bean definition for the above class:

<bean id ="bustedCar" class="com.car.SimpleCar"/>

To test the bean I used the below code:

public static void main(String[] args) {
    final XmlBeanFactory beanFactory = new XmlBeanFactory(
            new ClassPathResource("bean-interfaces.xml"));
    SimpleCar car = (SimpleCar) beanFactory.getBean("bustedCar");

The output of the code is :

the name of the bean is bustedCar
received the beanFactory org.springframework.beans.factory.xml.XmlBeanFactory@f7f540:
 defining beans [bustedCar]; root of factory hierarchy
Car is an empty car





Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s