java Spring BeanFactoryAware 和 ApplicationContextAware 有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2027200/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's the difference between Spring BeanFactoryAware and ApplicationContextAware?
提问by Matt
Both can be used to get bean instance, but which one is better to be used to implement?
两者都可以用来获取bean实例,但是用哪个更好实现呢?
回答by skaffman
If you need a reference to the BeanFactory, then use BeanFactoryAware. If you need a reference to the ApplicationContext, then use ApplicationContextAware.
如果您需要对 的引用BeanFactory,则使用BeanFactoryAware. 如果您需要对 的引用ApplicationContext,则使用ApplicationContextAware.
Note that the ApplicationContextinterface is a subclass of BeanFactory, and provides additional methods on top of the basic BeanFactoryinterface.
请注意,该ApplicationContext接口是 的子类BeanFactory,并在基本BeanFactory接口之上提供其他方法。
If all you need to do is call getBean(), then BeanFactoryis sufficient.
如果您需要做的只是调用getBean(),那么BeanFactory就足够了。
Note also that Spring 2.5+ provides a nicer way of getting yourself wired with a BeanFactoryor ApplicationContext, e.g.
另请注意,Spring 2.5+ 提供了一种更好的方式来让自己连接BeanFactory或连接ApplicationContext,例如
private @Autowired ApplicationContext appContext;
private @Autowired BeanFactory beanFactory;
No need for the XyzAwareinterfaces.
不需要XyzAware接口。
回答by perdian
An ApplicationContextis an extended version of a BeanFactoryand therefore offers additional functionalities.
AnApplicationContext是 a 的扩展版本,BeanFactory因此提供了额外的功能。
So whether to use ApplicationContextAwareor BeanFactoryAwareboils down to the question: Do you explicitely need any of the additional ApplicationContextfunctionalities? If you do implement ApplicationContextAwareotherwise stick to BeanFactoryAware.
因此,是使用ApplicationContextAware还是BeanFactoryAware归结为一个问题:您是否明确需要任何附加ApplicationContext功能?如果你确实实施,ApplicationContextAware否则坚持BeanFactoryAware.
回答by alasdairg
Do you require access to the additional features available on an ApplicationContext? If so, then you should of course use ApplicationContextAware. If not, BeanFactoryAwarewill be sufficient.
您是否需要访问 ApplicationContext 上可用的附加功能?如果是这样,那么您当然应该使用ApplicationContextAware。如果没有,BeanFactoryAware就足够了。
Amongst many other things, an ApplicationContext has additional methods for inspecting the beans e.g. containsBeanDefinition, getBeanDefinitionCount, getBeanDefinitionNames, getBeanNamesForType, getBeansOfTypethat 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

