Sunday, 5 June 2011

Using Spring's BeanNameAware Interface

Although it’s not a good idea to rely on the BeanNameAware as it adds a “potentially brittle dependence on external configuration”, it is a useful debugging feature especially in the situation where you need to instantiate a number of beans using the same class with each configured in a different way.

Implementing BeanNameAware couldn’t be simpler as demonstrated by the code below:

public class NameAwareBean implements BeanNameAware {
   
   
private static final Log log = LogFactory.getLog(NameAwareBean.class);
   
   
private String name;
   
   
public void setBeanName(String name) {
       
this.name = name;
   
}
   
   
public void businessMethod() {
       
       
if(log.isInfoEnabled()) {
           
log.info("Bean: [" + name + "] - Calling business method.");
       
}
    }  
}

When loading your Spring context, Spring will test the bean and if if implements BeanNameAware then it’ll call your bean’s setName(String name) method. When it does this, all you need to do is to store that method’s input argument in an instance variable and you’ll have the name of your bean for your bean’s lifetime.

In configuring your bean, you do not need to do anything special with your XML as the config below demonstrates:

<?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="myBeanName" class="example_3_spring_aware.bean_name_aware.NameAwareBean"/>
</beans>

No comments: