Spring BeanNameAware Interface

Spring BeanNameAware Interface

0 Comments

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

package guru.springframework.lifecyclebeans;

import org.springframework.beans.factory.BeanNameAware;
import org.springframework.stereotype.Component;

@Component
public class NameBean implements BeanNameAware {
    @Override
    public void setBeanName(String s) {
        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.

Demonstration of Using the BeanNameAware Interface

I have a short YouTube video showing the usage of the BeanNameAware Interface.

 

About jt

    You May Also Like

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    This site uses Akismet to reduce spam. Learn how your comment data is processed.