在Spring3中注入applicationContext的最佳实践 [英] Best Practise of injecting applicationContext in Spring3
问题描述
就像上面的标题一样,我对通过直接@Autowired注释注入applicationContext或在单例spring bean中实现ApplicationContextAware接口之间的优缺点感到困惑.
As in the title above, I am confused about pros cons between injecting applicationContext by directly @Autowired annnotation or implementing ApplicationContextAware interface in a singleton spring bean.
在哪种情况下,您更喜欢哪种?为什么?谢谢.
Which one do you prefer in which cases and why? Thanks.
推荐答案
实际上,两者都是不好的.它们都将您的应用程序绑定到Spring框架,从而颠倒了整个控制反转概念.在理想的世界中,您的应用程序根本不应该知道该对象是由ApplicationContext管理的.
Actually, both are bad. Both of them tie your application to the Spring framework, thus inverting the whole inversion-of-control concept. In an ideal world, your application should not be aware of being managed by an ApplicationContext at all.
一旦您选择违反此原则,则如何执行并不重要. ApplicationContextAware
是围绕至少从2.0版开始. @Autowired
是一种较新的机制,但是它们的工作方式几乎相同.我可能会选择ApplicationContextAware
,因为它在语义上清楚了它的含义.
Once you have chosen to violate this principle, it doesn't really matter how you do it. ApplicationContextAware
is the legacy version that has been around at least since Version 2.0. @Autowired
is a newer mechanism but they work in pretty much the same way. I'd probably go with ApplicationContextAware
, because it semantically makes clear what it is about.
这篇关于在Spring3中注入applicationContext的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!