Spring BeanNameAware Interface

Spring BeanNameAware Interface

During the creation of Spring Beans, you can obtain the name of the bean by implementing the Spring interface – BeanNameAware. Then during the creation of Spring beans, the Spring Context will inject the name it has set for the bean. This is the name the Spring Bean factory will use as a reference to the bean object.

While you this Spring interface is very easy to implement and use, I’m not sure you really wish to use it. From the javadoc for the BeanNameAware interface:

Interface to be implemented by beans that want to be aware of their bean name in a bean factory. Note that it is not usually recommended that an object depend on its bean name, as this represents a potentially brittle dependence on external configuration, as well as a possibly unnecessary dependence on a Spring API.

Generally, I prefer my Spring Beans to be unaware of the Spring environment. If your bean actually needs to know the name set for it within the Spring Context, you’re likely violating one more more of the SOLID Principles of Object Oriented Programming.

Implementing BeanNameAware

Implementing the BeanNameAware Interface is very simple, as you can see in the example below.

NameBean.java

1

2

3

4

5

6

7

8

9

10

11

12

packageguru.springframework.lifecyclebeans;

import org.springframework.beans.factory.BeanNameAware;

import org.springframework.stereotype.Component;

@Component

publicclassNameBeanimplementsBeanNameAware{

@Override

publicvoidsetBeanName(Strings){

System.out.println("Hello, my bean name is -"+s);

}

}

By implementing the BeanNameAware Interface, we provide a method on our class which will accept the string value of the bean name. In the example above, we simply output the bean name to the console.

Free Introduction to Spring Tutorial

Are you new to the Spring Framework? Checkout my Free Introduction to Spring Online Tutorial.