Saturday 19 March 2011

Spring : BeanNameAware Interface

Consider the following bean:

import org.springframework.beans.factory.BeanNameAware;

public class LifeCycledBean implements BeanNameAware
{
private String languageName;
private String beanName;

public LifeCycledBean ()
{
}

public String getLanguageName()
{
return languageName;
}

public void setLanguageName(String languageName)
{
this.languageName = languageName;
}

@Override
public void setBeanName(String beanName)
{
this.beanName = beanName;
}

public String getBeanName()
{
return beanName;
}
}


The above sample class provides one such implementation and the below client code uses the above class to know the name of the bean.

static void beanNameAwareTest()
{
Resource resource = new FileSystemResource("./src/resources/bean-lifecycle-1.xml");
BeanFactory beanFactory = new XmlBeanFactory(resource);
LanguageBean lifeCycledBean= (LanguageBean)beanFactory.getBean("lifeCycledBean");
System.out.println(lifeCycledBean.getLanguageName());
System.out.println(lifeCycledBean.getBeanName());
}



The following piece of Xml code snippet goes into the Xml Configuration file.

<bean id="javaLanguage" class="com.xxxx.LifeCycledBean">
<property name="lifeCycledBean" value="Java"/>
</bean>

No comments:

Post a Comment