This implementation is fairly trivial. Remember that BeanNameAware.setBeanName() is called before the
first instance of the bean is returned to your application via a call to ApplicationContext.getBean(), so
there is no need to check to see whether the bean name is available in the someOperation() method.
Listing 5-14 shows a simple configuration for this example (interaction/logging.xml).
Listing 5-14. Configuring the LoggingBean Example
<?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.1.xsd">
<bean id="loggingBean" class="com.apress.prospring3.ch5.interaction.LoggingBean"/>
</beans>
As you can see, no special configuration is required to take advantage of the BeanNameAware interface. In
Listing 5-15 you can see a simple example application that retrieves the LoggingBean instance from the
ApplicationContext and then calls the someOperation() method (interaction/logging.xml). class
Listing 5-15. The LoggingBeanExample Class
package com.apress.prospring3.ch5.interaction;
import org.springframework.context.support.GenericXmlApplicationContext;
public class LoggingBeanExample {
public static void main(String[] args) {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.load("classpath:interaction/logging.xml");
ctx.refresh();
LoggingBean bean = (LoggingBean) ctx.getBean("loggingBean");
bean.someOperation();
}
}
This example generates the following log output--notice the inclusion of the bean name in the log
message for the call to someOperation():
Loading XML bean definitions from class path resource [interaction/logging.xml]
Refreshing org.springframework.context.support.GenericXmlApplicationContext@5dccce3c: startup
date [Sun Sep 25 13:40:04 CST 2011]; root of context hierarchy
Pre-instantiating singletons in
org.springframework.beans.factory.support.DefaultListableBeanFactory@7ec5495e: defining beans
[loggingBean]; root of factory hierarchy
Bean [loggingBean] - someOperation()
Using the BeanNameAware interface is really quite simple, and it is put to good use when you are
improving the quality of your log messages. Avoid being tempted to give your bean names business
meaning just because you can access them; by doing so, you are coupling your classes to Spring for a
feature that brings negligible benefit. If your beans need some kind of name internally, then have them
implement an interface such as Nameable (which is specific to your application) with a method setName()
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home