Using ApplicationContextAware and BeanNameAware in Spring

We already know how to get an object from the Spring container using the getBean() method but sometimes we have the opposite need. That is, we want to use the Spring container in our object to have access to other objects in its container. Is there a way to do that?

I can say, Spring supports us to do that. By implementing the ApplicationContextAware interface, our object can use the Spring container.

Let’s take an example to see how it works.

Using ApplicationContextAware and BeanNameAware in Spring

In this example, we have an application that manages classes.

Here, I will declare two classes in the Spring container. The bean id of each class is the name of the class. As below:

Now, I have the need from Class A, I need to know the name of class B in the Spring container. To do this, you need to access the Spring container from class A first. Just add the implementation of the ApplicationContextAware interface as shown below:

OK, now from class A we can get the object of class B:

Here, perhaps, some of you will wonder why just implementing the ApplicationContextAware interface, the class object A can call the Spring container. Let me answer that: Spring uses the following code to automatically put the Spring container into the object needed.

As you can see, any object that is an instance of the ApplicationContextAware interface, during the runtime, that object will be automatically assigned the Spring container, here is the ApplicationContext.

Now back to our needs to take the name of class B.

To be able to use the bean id as the name of the class object B, we need to implement the BeanNameAware interface for this object. The code will look like the following:

Then, to get the name of class B, we just do the following:


Using ApplicationContextAware and BeanNameAware in Spring

Add Comment