我是Spring框架的新手,我一直在摆弄它,并把一些样本应用放在一起,目的是评估Spring MVC在即将到来的公司项目中的使用。到目前为止,我真的很喜欢Spring MVC,它看起来很容易使用,并鼓励你编写对单元测试非常友好的类。
作为练习,我正在为我的一个示例/测试项目编写一个主方法。我不清楚的一件事是BeanFactory和ApplicationContext之间的确切区别——哪个适合在哪些条件下使用?
我知道ApplicationContext扩展了BeanFactory,但是如果我只是编写一个简单的主方法,我是否需要ApplicationContext提供的额外功能呢?ApplicationContext究竟提供了什么样的额外功能?
除了回答“我应该在main()方法中使用哪个”之外,关于在这样的场景中应该使用哪个实现,是否有任何标准或指南?我的main()方法是否应该被编写成依赖于bean/应用程序配置的XML格式——这是一个安全的假设吗,还是我将用户锁定到某个特定的东西?
这个答案在web环境中会改变吗——如果我的任何类需要了解Spring,它们更可能需要ApplicationContext吗?
谢谢你的帮助。我知道很多问题都可以在参考手册中找到答案,但如果没有仔细阅读手册,我很难找到这两个接口的清晰分解以及各自的优缺点。
参考Spring Docs中的这个文档:
http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/beans.html#context-introduction-ctx-vs-beanfactory
5.15.1 bean工厂还是应用上下文?
使用ApplicationContext,除非你有很好的理由不这样做。
Because the ApplicationContext includes all functionality of the BeanFactory, it is generally recommended over the BeanFactory, except for a few situations such as in an Applet where memory consumption might be critical and a few extra kilobytes might make a difference. However, for most typical enterprise applications and systems, the ApplicationContext is what you will want to use. Spring 2.0 and later makes heavy use of the BeanPostProcessor extension point (to effect proxying and so on). If you use only a plain BeanFactory, a fair amount of support such as transactions and AOP will not take effect, at least not without some extra steps on your part. This situation could be confusing because nothing is actually wrong with the configuration.
在大多数情况下,首选ApplicationContext,除非需要节省资源,比如在移动应用程序上。
我不确定是否依赖于XML格式,但我非常确定ApplicationContext最常见的实现是XML实现,例如ClassPathXmlApplicationContext、XmlWebApplicationContext和FileSystemXmlApplicationContext。我只用过这三个。
如果您正在开发web应用程序,可以肯定地说,您将需要使用XmlWebApplicationContext。
如果您希望bean能够感知Spring,您可以让它们为此实现BeanFactoryAware和/或ApplicationContextAware,因此您可以使用BeanFactory或ApplicationContext并选择实现哪个接口。
BeanFactory和ApplicationContext的区别如下:
BeanFactory uses lazy initialization but ApplicationContext uses eager initialization. In case of BeanFactory, bean is created when you call getBeans() method, but bean is created upfront in case of ApplicationContext when the ApplicationContext object is created.
BeanFactory explicitly provide a resource object using syntax but ApplicationContext creates and manages resource objects on its own.
BeanFactory doesnt support internatiolization but ApplicationContext supports internationalization.
With BeanFactory annotation based dependency injection is not supported but annotation based dependency injection is supported in ApplicationContext.
使用BeanFactory:
BeanFactory beanfactory = new XMLBeanFactory(new FileSystemResource("spring.xml"));
Triangle triangle =(Triangle)beanFactory.getBean("triangle");
使用ApplicationContext:
ApplicationContext context = new ClassPathXMLApplicationContext("spring.xml")
Triangle triangle =(Triangle)context.getBean("triangle");