Home  >  Spring

Spring BeanNameAware Example

By Arvind Rai, October 28, 2021
On this page we will provide Spring BeanNameAware example. The BeanNameAware interface is implemented by beans that want to be aware of their bean name in a bean factory. The BeanNameAware has setBeanName method that needs to be overriden by beans.

Implement BeanNameAware

The BeanNameAware has following method.
void setBeanName(String name) 
This method sets the name of the bean in the bean factory that created this bean. The setBeanName is invoked after population of normal bean but before an init callback.




Find the code to use BeanNameAware.
Book.java
package com.concretepage;
import org.springframework.beans.factory.BeanNameAware;
public class Book implements BeanNameAware {
	private String bookName;
	@Override
	public void setBeanName(String beanName) {
		System.out.println(beanName +" bean has been initialized." );		
	}
	public Book(String bookName) {
		System.out.println("--Inside Constructor--");
		this.bookName = bookName;
	}
	public String getBookName() {
		return bookName;
	}
} 

Configure Bean

We are using XML configuration to configure our bean.
app-conf.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="myBook" class="com.concretepage.Book">
       <constructor-arg name="bookName" value="Mahabharat"/>
    </bean>
</beans> 

Run Demo Application

Find the class to run the demo.
SpringDemo.java
package com.concretepage;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringDemo {
	public static void main(String[] args) {
		AbstractApplicationContext  context = new ClassPathXmlApplicationContext("app-conf.xml");
		Book book = (Book)context.getBean("myBook");
		System.out.println("Book Name:" + book.getBookName());
		context.close();
	}
}  
We observe in output that first constructor is called and after that setBeanName() is called.
--Inside Constructor--
myBook bean has been initialized.
Book Name:Mahabharat 

Reference

Interface BeanNameAware

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI










©2022 concretepage.com | Privacy Policy | Contact Us