Spring BeanNameAware Interface
0 CommentsLast Updated on June 16, 2019 by Simanta
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
Demonstration of Using the BeanNameAware Interface
I have a short YouTube video showing the usage of the BeanNameAware
Interface.