tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Spring > Core > Bean Name Aware

Bean Name Aware 

Spring Inversion of Control (IoC) also known as Dependency Injection (DI) is a process by which objects define their dependencies with collaborating objects. Spring provides BeanNameAware interface which allows us to have access to name of the bean defined in bean definition.

BeanNameAware.java  
package org.springframework.beans.factory;

public abstract interface BeanNameAware
{
  public abstract void setBeanName(String paramString);
}
File Name  :  
/SpringCore001/conf/aware/bean_name.xml 

File Name  :  
com/bethecoder/tutorials/spring3/basic/SimpleBeanNameAware.java 
   
package com.bethecoder.tutorials.spring3.basic;

import org.springframework.beans.factory.BeanNameAware;

public class SimpleBeanNameAware implements BeanNameAware {

  private String simpleProp;

  public String getSimpleProp() {
    return simpleProp;
  }

  public void setSimpleProp(String simpleProp) {
    this.simpleProp = simpleProp;
  }

  @Override
  public void setBeanName(String name) {
    System.out.println("In setBeanName : " + name);
    
    //Initialize property with bean name 
    this.simpleProp = name;
  }
  
  public String toString() {
    return "SimpleBeanNameAware[" + simpleProp + "]";
  }
}
   

File Name  :  
com/bethecoder/tutorials/spring3/tests/aware/BeanNameAwareTest.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.spring3.tests.aware;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.bethecoder.tutorials.spring3.basic.SimpleBeanNameAware;

public class BeanNameAwareTest {

  /**
   @param args
   */
  public static void main(String[] args) {

    System.out.println("Initializing ApplicationContext");
    ApplicationContext factory = new ClassPathXmlApplicationContext("bean_name.xml");
    System.out.println("ApplicationContext Initialized");
    
    SimpleBeanNameAware first = (SimpleBeanNameAwarefactory.getBean("first");
    System.out.println(first);

    SimpleBeanNameAware second = (SimpleBeanNameAwarefactory.getBean("second");
    System.out.println(second);

  }

}
   

It gives the following output,
Initializing ApplicationContext
ApplicationContext Initialized

In setBeanName : first
SimpleBeanNameAware[first]

In setBeanName : second
SimpleBeanNameAware[second]



 
  


  
bl  br