Making Your Beans "Spring Aware"
One of the biggest selling points of Dependency Injection over Dependency Lookup as a mechanism for
achieving Inversion of Control is that your beans do not need to be aware of the implementation of the
container that is managing them. To a bean that uses constructor or setter injection, the Spring container
is the same as the container provided by Google Guice or PicoContainer. However, in certain
circumstances, you may need a bean that is using Dependency Injection to obtain its dependencies so it
can interact with the container for some other reason. An example of this may be a bean that
automatically configures a shutdown hook for you, and thus it needs access to the ApplicationContext. In
other cases, a bean may want to know what its name (i.e., the bean name that was assigned within the
current ApplicationContext) is so it can perform some additional processing based on this name.
That said, this feature is really intended for internal Spring use. Giving the name some kind of
business meaning is generally a bad idea and can lead to configuration problems where bean names
have to be artificially manipulated to support their business meaning. However, we have found that
being able to have a bean find out its name at runtime is really useful for logging. Consider a situation
where you have many beans of the same type running under different configurations. The bean name
can be included in log messages to help you differentiate between which one is generating errors and
which ones are working fine when something goes wrong.
Using the BeanNameAware Interface
The BeanNameAware interface, which can be implemented by a bean that wants to obtain its own name,
has a single method: setBeanName(String). Spring calls the setBeanName() method after it has finished
configuring your bean but before any life-cycle callbacks (initialization or destroy) are called (refer to
Figure 5-1). In most cases, the implementation of the setBeanName() interface is just a single line that
stores the value passed in by the container in a field for use later. Listing 5-13 shows a simple bean that
obtains its name using BeanNameAware and then later uses this bean name when writing log messages.
Listing 5-13. Implementing BeanNameAware
package com.apress.prospring3.ch5.interaction;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.BeanNameAware;
public class LoggingBean implements BeanNameAware {
private static final Log log = LogFactory.getLog(LoggingBean.class);
private String beanName = null;
public void setBeanName(String beanName) {
this.beanName = beanName;
}
public void someOperation() {
if(log.isInfoEnabled()) {
log.info("Bean [" + beanName + "] - someOperation()");
}
}
}
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home