Tuesday, August 24, 2010

Spring aware interfaces

For the most part, beans running in the Spring container, They don't know (or
even need to know) their names or even that they are running within a Spring
container. This is usually a good thing because if a bean is aware of the container,
then it becomes coupled with Spring and may not be able to exist outside of the container.

A well designed component should not have direct dependencies on its container,  
But sometimes, beans need to know more. Sometimes they need to know the
truth who they are and where they are running.

This capability comes in the form of the
Bean-NameAware,
BeanFactoryAware,

and ApplicationContextAware interfaces .

By implementing these three interfaces,

beans can be made aware of their name, their BeanFactory, and their ApplicationContext, respectively.

However, by implementing these interfaces, a bean becomes coupled with Spring.

The Spring container tells a bean what its name is through the BeanNameAware
interface.

public interface BeanNameAware {
  void setBeanName(String name);
}

Spring's ApplicationContextAware and BeanFactoryAware interfaces enable a
bean to be aware of its container. These interfaces declare a setApplication-
Context() method and a setBeanFactory() method, respectively.

When to use?


your bean needs access to parameterized text messages in a message source.
Or maybe it needs to be able to publish application
events for application event listeners to respond to. Whatever the case, your bean
should be aware of the container in which it lives.
Spring,Java,Spring FAQ,

No comments: