Home  >  Spring Core

Example of BeanNameAware in Spring

By Arvind Rai, April 19, 2013
On this page we will provide example of BeanNameAware in spring. BeanNameAware belongs to the package org.springframework.beans.factory. BeanNameAware can be used to set bean name. The class has to implement interface BeanNameAware and override its method setBeanName(String beanName). When the bean is loaded by spring container, the bean name is set to this method. Find the example below.

Implement BeanNameAware

We are creating a bean that is implementing BeanNameAware interface and overriding method setBeanName().
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 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> 

Gradle File

Find gradle file to resolve JAR dependencies.
build.gradle
apply plugin: 'java'
apply plugin: 'eclipse'
archivesBaseName = 'SpringDemo'
version = '1' 
repositories {
    mavenCentral()
}
dependencies {
    compile 'org.springframework.boot:spring-boot-starter:1.2.7.RELEASE'
}  

Run Demo

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 will observe in output that first constructor is called and after that setBeanName() is called.
--Inside Constructor--
myBook bean has been initialized.
Book Name:Mahabharat 

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us