Tuesday, November 26, 2013

Both can be used to get bean instance, but which one is better to be used to implement?
share|improve this question
add comment

3 Answers

up vote19down voteaccepted
If you need a reference to the BeanFactory, then use BeanFactoryAware. If you need a reference to the ApplicationContext, then use ApplicationContextAware.
Note that the ApplicationContext interface is a subclass of BeanFactory, and provides additional methods on top of the basic BeanFactory interface.
If all you need to do is call getBean(), then BeanFactory is sufficient.
Note also that Spring 2.5+ provides a nicer way of getting yourself wired with a BeanFactory orApplicationContext, e.g.
private @Autowired ApplicationContext appContext;
private @Autowired BeanFactory beanFactory;
No need for the XyzAware interfaces.
share|improve this answer
 
In autowired case is it possible to catch appContext/beanFactory set event? In constructor appContext/beanFactory has not set yet... –  Simi Mar 12 '12 at 15:43
add comment
An ApplicationContext is an extended version of a BeanFactory and therefore offers additional functionalities.
So whether to use ApplicationContextAware or BeanFactoryAware boils down to the question: Do you explicitely need any of the additional ApplicationContext functionalities? If you do implementApplicationContextAware otherwise stick to BeanFactoryAware.
share|improve this answer
add comment
Do you require access to the additional features available on an ApplicationContext? If so, then you should of course use ApplicationContextAware. If not, BeanFactoryAware will be sufficient.
Amongst many other things, an ApplicationContext has additional methods for inspecting the beans e.g.containsBeanDefinitiongetBeanDefinitionCountgetBeanDefinitionNames,getBeanNamesForTypegetBeansOfType that may be useful to you and which are not available onBeanFactory
I usually implement ApplicationContextAware
share|improve this answer

No comments: