and then give each bean a name using Dependency Injection. This way, you can keep the names you use
for configuration concise, and you won't need to manipulate your configuration unnecessarily to give
your beans names with business meaning.
Using the ApplicationContextAware Interface
Using the ApplicationContextAware interface, it is possible for your beans to get a reference to the
ApplicationContext that configured them. The main reason this interface was created was to allow a bean
to access Spring's ApplicationContext in your application, such as acquire other Spring beans
programmatically, using getBean(). You should, however, avoid this practice and use Dependency
Injection to provide your beans with their collaborators. If you use the lookup-based getBean() approach
to obtain dependencies when you can use Dependency Injection, you are adding unnecessary complexity
to your beans and coupling them to the Spring Framework without good reason.
Of course, the ApplicationContext isn't just used to look up beans; it performs a great many other
tasks. As you saw previously, one of these tasks is to destroy all singletons, notifying each of them in turn
before doing so. In the previous section, you saw how to create a shutdown hook to ensure that the
ApplicationContext is instructed to destroy all singletons before the application shuts down. By using the
ApplicationContextAware interface, you can build a bean that can be configured in an ApplicationContext
to create and configure a shutdown hook bean automatically. Listing 5-16 shows the code for this bean.
Listing 5-16. The ShutdownHookBean Class
package com.apress.prospring3.ch5.interaction;
import
org.springframework.beans.BeansException;
import
org.springframework.context.ApplicationContext;
import
org.springframework.context.ApplicationContextAware;
import
org.springframework.context.support.GenericApplicationContext;
public class ShutdownHookBean implements ApplicationContextAware {
private ApplicationContext ctx;
public void setApplicationContext(ApplicationContext ctx)
throws BeansException {
if (ctx instanceof GenericApplicationContext) {
((GenericApplicationContext) ctx).registerShutdownHook();
}
}
}
Most of this code should seem familiar to you by now. The ApplicationContextAware interface
defines a single method, setApplicationContext(ApplicationContext), which Spring calls to pass your
bean a reference to its ApplicationContext. In Listing 5-16, the ShutdownHookBean class checks to see
whether the ApplicationContext is of type GenericApplicationContext, meaning it supports the
registerShutdownHook() method; if it does, it will register a shutdown hook to the ApplicationContext.
Listing 5-17 shows how to configure this bean to work with the DestructiveBeanWithInterface bean
used in the previous section (interaction/shutdownHook.xml).
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home