[英]What's the difference between Spring BeanFactoryAware and ApplicationContextAware?
两者都可以用来获取bean实例,但哪一个更适合用来实现?
If you need a reference to the BeanFactory
, then use BeanFactoryAware
. 如果需要对
BeanFactory
的引用,请使用BeanFactoryAware
。 If you need a reference to the ApplicationContext
, then use ApplicationContextAware
. 如果需要对
ApplicationContext
的引用,请使用ApplicationContextAware
。
Note that the ApplicationContext
interface is a subclass of BeanFactory
, and provides additional methods on top of the basic BeanFactory
interface. 请注意,
ApplicationContext
接口是BeanFactory
的子类,并在基本BeanFactory
接口之上提供其他方法。
If all you need to do is call getBean()
, then BeanFactory
is sufficient. 如果你需要做的只是调用
getBean()
,那么BeanFactory
就足够了。
Note also that Spring 2.5+ provides a nicer way of getting yourself wired with a BeanFactory
or ApplicationContext
, eg 另请注意,Spring 2.5+提供了一种更好的方式来使用
BeanFactory
或ApplicationContext
连接自己,例如
private @Autowired ApplicationContext appContext;
private @Autowired BeanFactory beanFactory;
No need for the XyzAware
interfaces. 无需
XyzAware
接口。
An ApplicationContext
is an extended version of a BeanFactory
and therefore offers additional functionalities. ApplicationContext
是BeanFactory
的扩展版本,因此提供了其他功能。
So whether to use ApplicationContextAware
or BeanFactoryAware
boils down to the question: Do you explicitely need any of the additional ApplicationContext
functionalities? 因此,是否使用
ApplicationContextAware
或BeanFactoryAware
归结为以下问题:您是否明确需要任何其他ApplicationContext
功能? If you do implement ApplicationContextAware
otherwise stick to BeanFactoryAware
. 如果你确实实现了
ApplicationContextAware
否则坚持使用BeanFactoryAware
。
Do you require access to the additional features available on an ApplicationContext? 您是否需要访问ApplicationContext上提供的其他功能? If so, then you should of course use ApplicationContextAware .
如果是这样,那么你当然应该使用ApplicationContextAware 。 If not, BeanFactoryAware will be sufficient.
如果没有, BeanFactoryAware就足够了。
Amongst many other things, an ApplicationContext has additional methods for inspecting the beans eg containsBeanDefinition , getBeanDefinitionCount , getBeanDefinitionNames , getBeanNamesForType , getBeansOfType that may be useful to you and which are not available on BeanFactory 在许多其他事情中,ApplicationContext还有其他检查bean的方法,例如containsBeanDefinition , getBeanDefinitionCount , getBeanDefinitionNames , getBeanNamesForType , getBeansOfType可能对你有用,哪些在BeanFactory上不可用
I usually implement ApplicationContextAware 我通常实现ApplicationContextAware
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.