Sometimes, I find some class na开发者_JAVA百科mes including Aware such as ApplicationContextAware
and MessageSourceAware
(spring). Does this Aware have any special meanings or is it a famous rule?
Those are not classes, are interfaces. The name is just a convention on Spring meaning that some special framework object is going to be injected to that class if it is managed by the framework.
Directly from the docs of ApplicationContextAware:
Interface to be implemented by any object that wishes to be notified of the ApplicationContext that it runs in.
In this case, the bean that implements this interface will get a reference to the ApplicationContext managing the application.
Appending adjectives like "aware" to the end is a naming scheme often used for Java interfaces. This can then be implemented by classes, and the resulting is code which is more fluent to read for human beings, like
class Broker implements ApplicationContextAware { /* ... */ }
where it's quite easy to see that this class is a broker for something, and it knows how to deal with application contexts. Besides that, the "Aware" suffix has no special meaning from the Java (compiler) perspective.
The interfaces you cite seem to be a Spring-specific convention for allowing objects to interact with the dependency injection container that created them. By implementing the interface, a class signals that it wants certain information from the container and at the same time provides a method through which to pass that information.
I'd see it simply as an attempt to find a generic name for an interface that offers such functionality, not necessarily a strong convention with a specific technical meaning.
The concept of aware interfaces:
If I want the reference of objects of spring classes like XmlBeanFactory
,ApplicationContext
... In 2 or more classes, then there are 3 possible ways are there.
- creating 2
BeanFactories
in two classes. - creating at one class and sharing to all required classes .
In the 1st case ,we are unnecessarely creating 2 BeanFactories. In the 2nd case, classes are tightly coupled with each other.
- If our class implements
BeanFactoryAware
interface and overrides the contractual method calledpublic BeanFactory setBeanFactory(BeanFactory factory)
thenIOC container
see that special interface and callssetBeanFactory
method by settingBeanFactory
reference to that.
In 3. case above two problems are not there.
精彩评论