Searching...
Thursday, 25 September 2014

Spring BeanNameAware Example

02:31
BeanNameAware Interface to be implemented by beans that want to be aware of their bean name in a bean factory. If a bean in spring implements BeanNameAware then that bean has to implement a method that is setBeanName. And when that bean is loaded in spring container, the name is set to this method.
Here is an example to implement this interface and printing the name when it is loaded.

 

Student.java (Which implements BeanNameAware)

import org.springframework.beans.factory.BeanNameAware;

public class Student implements BeanNameAware {
    @Override
    public void setBeanName(String name) {
        System.out.println("Setting bean name " + name);

    }

}

application-context.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-3.0.xsd">

    <bean id="student" class="com.pretech.test.Student" />
</beans>
Test class
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BeanNameAwareTest {

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext(
                "application-context.xml");
    }
}
Output
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@48a930: defining beans [student]; root of factory hierarchy
Setting bean name student

0 comments: