BeanFactory 与 ApplicationContext
我对 Spring 框架还很陌生,我一直在使用它,并将一些示例应用程序放在一起,以便评估 Spring MVC 在即将推出的公司项目中的使用。 到目前为止,我真的很喜欢 Spring MVC 中的内容,它看起来非常易于使用,并鼓励您编写非常适合单元测试的类。
作为练习,我正在为我的一个示例/测试项目编写一个主要方法。 我不清楚的一件事是 BeanFactory 和 ApplicationContext 之间的确切区别 - 哪个适合在哪些条件下使用?
我知道 ApplicationContext
扩展了 BeanFactory
,但如果我只是编写一个简单的 main 方法,我是否需要 ApplicationContext
提供的额外功能? ApplicationContext
到底提供了什么样的额外功能?
除了回答“我应该在 main() 方法中使用哪个”之外,对于在这种情况下我应该使用哪种实现,是否有任何标准或指南? 我的 main() 方法是否应该编写为依赖于 XML 格式的 bean/应用程序配置 - 这是一个安全的假设,还是我将用户锁定在特定的内容中?
这个答案在 Web 环境中是否会改变 - 如果我的任何类需要了解 Spring,它们是否更有可能需要 ApplicationContext
?
谢谢你的帮助。 我知道很多这样的问题可能在参考手册中得到了解答,但是如果不仔细阅读手册,我很难找到这两个接口的明确分类以及每个接口的优缺点。
I'm pretty new to the Spring Framework, I've been playing around with it and putting a few samples apps together for the purposes of evaluating Spring MVC for use in an upcoming company project. So far I really like what I see in Spring MVC, seems very easy to use and encourages you to write classes that are very unit test-friendly.
Just as an exercise, I'm writing a main method for one of my sample/test projects. One thing I'm unclear about is the exact differences between BeanFactory
and ApplicationContext
- which is appropriate to use in which conditions?
I understand that ApplicationContext
extends BeanFactory
, but if I'm just writing a simple main method, do I need the extra functionality that ApplicationContext
provides? And just exactly what kind of extra functionality does ApplicationContext
provide?
In addition to answering "which should I use in a main() method", are there any standards or guidelines as far as which implementation I should use in such a scenario? Should my main() method be written to depend on the bean/application configuration to be in XML format - is that a safe assumption, or am I locking the user into something specific?
And does this answer change in a web environment - if any of my classes needed to be aware of Spring, are they more likely to need ApplicationContext
?
Thanks for any help. I know a lot of these questions are probably answered in the reference manual, but I'm having a hard time finding a clear breakdown of these two interfaces and the pros/cons of each without reading thru the manual with a fine-tooth comb.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(22)
spring 文档在这方面非常出色: 3.8.1。 BeanFactory 还是 ApplicationContext?。
他们有一个比较表,我将发布一个片段:
Bean Factory
Application Context
因此,如果您需要在应用程序上下文方面呈现的任何点,您应该使用 ApplicationContext。
The spring docs are great on this: 3.8.1. BeanFactory or ApplicationContext?.
They have a table with a comparison, I'll post a snippet:
Bean Factory
Application Context
So if you need any of the points presented on the Application Context side, you should use ApplicationContext.
FileSystemXmlApplicationContext
通过完整路径加载的 Bean。ClassPathXmlApplicationContext
通过 CLASSPATH 加载的 BeanXMLWebApplicationContext
和AnnotationConfigWebApplicationContext
通过 Web 应用程序上下文加载的 Bean。AnnotationConfigApplicationContext
从基于注释的配置加载 Spring bean。例如:
ApplicationContext
是由web.xml
和中定义的
在ContextLoaderListener
或ContextLoaderServlet
初始化的容器ContextLoaderPluginstruts-config.xml
中定义。注意:
XmlBeanFactory
是从 Spring 3.1 开始已弃用,取而代之的是DefaultListableBeanFactory
和XmlBeanDefinitionReader
。FileSystemXmlApplicationContext
Beans loaded through the full path.ClassPathXmlApplicationContext
Beans loaded through the CLASSPATHXMLWebApplicationContext
andAnnotationConfigWebApplicationContext
beans loaded through the web application context.AnnotationConfigApplicationContext
Loading Spring beans from Annotation based configuration.example:
ApplicationContext
is the container initialized by aContextLoaderListener
orContextLoaderServlet
defined in aweb.xml
andContextLoaderPlugin
defined instruts-config.xml
.Note:
XmlBeanFactory
is deprecated as of Spring 3.1 in favor ofDefaultListableBeanFactory
andXmlBeanDefinitionReader
.对我来说,选择
BeanFactory
而不是ApplicationContext
的主要区别似乎是ApplicationContext
将预先实例化所有 bean。 来自 Spring 文档:鉴于此,我最初选择 BeanFactory 来用于集成/性能测试,因为我不想加载整个应用程序来测试隔离的 bean。 然而——如果我错了,有人会纠正我——
BeanFactory
不支持classpath
XML 配置。 因此,BeanFactory
和ApplicationContext
各自提供了我想要的关键功能,但两者都没有。据我所知,文档中有关覆盖默认实例化行为的注释发生在配置中,并且是针对每个 bean 的,因此我不能只在 XML 文件中设置“lazy-init”属性,否则我就坚持维护一个版本用于测试和一个版本用于部署。
我最终所做的是扩展 ClassPathXmlApplicationContext 来延迟加载 bean,以便在测试中使用,如下所示:
To me, the primary difference to choose
BeanFactory
overApplicationContext
seems to be thatApplicationContext
will pre-instantiate all of the beans. From the Spring docs:Given this, I initially chose
BeanFactory
for use in integration/performance tests since I didn't want to load the entire application for testing isolated beans. However -- and somebody correct me if I'm wrong --BeanFactory
doesn't supportclasspath
XML configuration. SoBeanFactory
andApplicationContext
each provide a crucial feature I wanted, but neither did both.Near as I can tell, the note in the documentation about overriding default instantiation behavior takes place in the configuration, and it's per-bean, so I can't just set the "lazy-init" attribute in the XML file or I'm stuck maintaining a version of it for test and one for deployment.
What I ended up doing was extending
ClassPathXmlApplicationContext
to lazily load beans for use in tests like so:要添加 Miguel Ping 的回答,这里是 文档中的另一部分也回答了这个问题:
(将此帖子发布给任何可能阅读此问题的未来 Spring 新手)
To add onto what Miguel Ping answered, here is another section from the documentation that answers this as well:
(posting this for any future Spring novices who might read this question)
ApplicationContext
是比BeanFactory
更优选的方式BeanFactory
被替换为ApplicationContext
。 但为了向后兼容,BeanFactory
仍然存在ApplicationContext 扩展了 BeanFactory
并具有以下优点ApplicationContext
is more preferred way thanBeanFactory
In new Spring versions
BeanFactory
is replaced withApplicationContext
. But stillBeanFactory
exists for backward compatabilityApplicationContext extends BeanFactory
and has the following benefits应用程序上下文:
它加载在 spring 配置文件中配置的 spring bean,并在容器启动时管理 spring bean 的生命周期。它不会等到 getBean("springbeanref") 被调用。
BeanFactory
它加载在spring配置文件中配置的spring bean,当我们调用getBean("springbeanref")时管理spring bean的生命周期。所以当我们调用getBean("springbeanref")时 在 spring bean 生命周期开始时。
ApplicationContext:
It loads spring beans configured in spring configuration file,and manages the life cycle of the spring bean as and WHEN CONTAINER STARTS.It won't wait until getBean("springbeanref") is called.
BeanFactory
It loads spring beans configured in spring configuration file,manages the life cycle of the spring bean when we call the getBean("springbeanref").So when we call the getBean("springbeanref") at the time of spring bean life cycle starts.
我认为最好始终使用 ApplicationContext,除非您处于移动环境中,就像其他人已经说过的那样。 ApplicationContext有更多的功能,你肯定想使用PostProcessor,如RequiredAnnotationBeanPostProcessor,AutowiredAnnotationBeanPostProcessor和CommonAnnotationBeanPostProcessor,这将帮助你简化你的Spring配置文件,你可以在你的bean中使用@Required,@PostConstruct,@Resource等注解。
即使您不使用 ApplicationContext 提供的所有内容,最好还是使用它,然后如果您决定使用某些资源内容(例如消息或后处理器)或其他模式来添加事务建议等,您已经有一个 ApplicationContext 并且不需要更改任何代码。
如果您正在编写独立应用程序,请使用 ClassPathXmlApplicationContext 在主方法中加载 ApplicationContext,并获取主 bean 并调用其 run() (或任何方法)来启动您的应用程序。 如果您正在编写 Web 应用程序,请在 web.xml 中使用 ContextLoaderListener,以便它创建 ApplicationContext,然后您可以从 ServletContext 获取它,无论您是否使用 JSP、JSF、JSTL、struts、Tapestry 等 另外,
请记住,您可以使用多个 Spring 配置文件,并且可以通过在构造函数中列出所有文件(或在 ContextLoaderListener 的上下文参数中列出它们)来创建 ApplicationContext,也可以仅加载一个主配置文件有导入语句。 您可以使用将一个 Spring 配置文件导入到另一个 Spring 配置文件中。 当您在 main 方法中以编程方式创建 ApplicationContext 并仅加载一个 Spring 配置文件时,这非常有用。
I think it's better to always use ApplicationContext, unless you're in a mobile environment like someone else said already. ApplicationContext has more functionality and you definitely want to use the PostProcessors such as RequiredAnnotationBeanPostProcessor, AutowiredAnnotationBeanPostProcessor and CommonAnnotationBeanPostProcessor, which will help you simplify your Spring configuration files, and you can use annotations such as @Required, @PostConstruct, @Resource, etc in your beans.
Even if you don't use all the stuff ApplicationContext offers, it's better to use it anyway, and then later if you decide to use some resource stuff such as messages or post processors, or the other schema to add transactional advices and such, you will already have an ApplicationContext and won't need to change any code.
If you're writing a standalone app, load the ApplicationContext in your main method, using a ClassPathXmlApplicationContext, and get the main bean and invoke its run() (or whatever method) to start your app. If you're writing a web app, use the ContextLoaderListener in web.xml so that it creates the ApplicationContext and you can later get it from the ServletContext, regardless of whether you're using JSP, JSF, JSTL, struts, Tapestry, etc.
Also, remember you can use multiple Spring configuration files and you can either create the ApplicationContext by listing all the files in the constructor (or listing them in the context-param for the ContextLoaderListener), or you can just load a main config file which has import statements. You can import a Spring configuration file into another Spring configuration file by using <import resource="otherfile.xml" /> which is very useful when you programmatically create the ApplicationContext in the main method and load only one Spring config file.
BeanFactory 和 ApplicationContext 之间的区别如下:
使用 BeanFactory:
使用 ApplicationContext:
Difference between BeanFactory and ApplicationContext are following:
Using BeanFactory:
Using ApplicationContext:
在大多数情况下,除非您需要节省资源(例如在移动应用程序上),否则首选 ApplicationContext。
我不确定是否依赖 XML 格式,但我很确定 ApplicationContext 最常见的实现是 XML 实现,例如 ClassPathXmlApplicationContext、XmlWebApplicationContext 和 FileSystemXmlApplicationContext。 这是我唯一用过的三个。
如果您开发 Web 应用程序,可以肯定地说您将需要使用 XmlWebApplicationContext。
如果您希望您的bean了解Spring,您可以让它们实现BeanFactoryAware和/或ApplicationContextAware,这样您就可以使用BeanFactory或ApplicationContext并选择要实现的接口。
For the most part, ApplicationContext is preferred unless you need to save resources, like on a mobile application.
I'm not sure about depending on XML format, but I'm pretty sure the most common implementations of ApplicationContext are the XML ones such as ClassPathXmlApplicationContext, XmlWebApplicationContext, and FileSystemXmlApplicationContext. Those are the only three I've ever used.
If your developing a web app, it's safe to say you'll need to use XmlWebApplicationContext.
If you want your beans to be aware of Spring, you can have them implement BeanFactoryAware and/or ApplicationContextAware for that, so you can use either BeanFactory or ApplicationContext and choose which interface to implement.
通过两种方式创建 spring 容器对象
两者都是接口,
使用实现类我们可以为 Spring 容器创建对象,
区别在于
BeanFactory :
不支持基于 Annotation 的依赖注入。
不支持 I18N。
默认支持延迟加载。
它不允许配置多个配置文件。
例如: BeanFactory context=new XmlBeanFactory(new Resource("applicationContext.xml"));
ApplicationContext
支持基于注解的依赖注入。-@Autowired、@PreDestroy
支持 I18N
默认支持主动加载。
它允许配置多个配置文件。
例如:
ApplicationContext context=new ClasspathXmlApplicationContext("applicationContext.xml");
Basically we can create spring container object in two ways
both are the interfaces,
using implementation classes we can create object for spring container
coming to the differences
BeanFactory :
Does not support the Annotation based dependency Injection.
Doesn't Support I18N.
By default its support Lazy loading.
it doesn't allow configure to multiple configuration files.
ex: BeanFactory context=new XmlBeanFactory(new Resource("applicationContext.xml"));
ApplicationContext
Support Annotation based dependency Injection.-@Autowired, @PreDestroy
Support I18N
Its By default support Aggresive loading.
It allow to configure multiple configuration files.
ex:
ApplicationContext context=new ClasspathXmlApplicationContext("applicationContext.xml");
BeanFactory 和 ApplicationContext 都是从 spring IOC 容器中获取 bean 的方法,但仍然存在一些差异。
BeanFactory 是实例化、配置和管理许多 bean 的实际容器。 这些 Bean 通常相互协作,因此它们之间具有依赖关系。 这些依赖关系反映在 BeanFactory 使用的配置数据中。
BeanFactory和ApplicationContext都是Java接口,并且ApplicationContext扩展了BeanFactory。 两者都是使用XML配置文件进行配置。 简而言之,BeanFactory 提供基本的控制反转 (IoC) 和依赖注入 (DI) 功能,而 ApplicationContext 提供高级功能。
一个BeanFactory由接口“org.springframework.beans.factory”表示,其中BeanFactory有多种实现。
区别
BeanFactory在调用getBean()方法时实例化bean,而ApplicationContext在容器启动时实例化Singleton bean,它不会等待getBean() 被调用。
BeanFactory 不提供对国际化的支持,但 ApplicationContext 提供对国际化的支持。
BeanFactory 与 ApplicationContext 之间的另一个区别是能够将事件发布到注册为侦听器的 Bean。
BeanFactory接口的流行实现之一是XMLBeanFactory,而ApplicationContext接口的流行实现之一是ClassPathXmlApplicationContext strong>。
如果您使用自动装配并使用 BeanFactory,则需要使用 API 注册 AutoWiredBeanPostProcessor,如果您使用 ApplicationContext,则可以在 XML 中配置该 API。强>。 总之,BeanFactory 适合测试和非生产使用,但 ApplicationContext 是功能更丰富的容器实现,应该比 BeanFactory 更受青睐
< strong>BeanFactory默认支持Lazy加载,ApplicationContext默认支持Aggresive加载。
BeanFactory and ApplicationContext both are ways to get beans from your spring IOC container but still there are some difference.
BeanFactory is the actual container which instantiates, configures, and manages a number of bean's. These beans are typically collaborate with one another, and thus have dependencies between themselves. These dependencies are reflected in the configuration data used by the BeanFactory.
BeanFactory and ApplicationContext both are Java interfaces and ApplicationContext extends BeanFactory. Both of them are configuration using XML configuration files. In short BeanFactory provides basic Inversion of control(IoC) and Dependency Injection (DI) features while ApplicationContext provides advanced features.
A BeanFactory is represented by the interface "org.springframework.beans.factory" Where BeanFactory, for which there are multiple implementations.
DIFFERENCE
BeanFactory instantiate bean when you call getBean() method while ApplicationContext instantiate Singleton bean when container is started, It doesn't wait for getBean() to be called.
BeanFactory doesn't provide support for internationalization but ApplicationContext provides support for it.
Another difference between BeanFactory vs ApplicationContext is ability to publish event to beans that are registered as listener.
One of the popular implementation of BeanFactory interface is XMLBeanFactory while one of the popular implementation of ApplicationContext interface is ClassPathXmlApplicationContext.
If you are using auto wiring and using BeanFactory than you need to register AutoWiredBeanPostProcessor using API which you can configure in XML if you are using ApplicationContext. In summary BeanFactory is OK for testing and non production use but ApplicationContext is more feature rich container implementation and should be favored over BeanFactory
BeanFactory by default its support Lazy loading and ApplicationContext by default support Aggresive loading.
Bean Factory 与应用程序上下文的功能矩阵 源自 spring 文档
BeanFacotry 和 ApplicationContext 功能的屏幕截图
Feature Matrix of Bean Factory vs Application Context sourced from spring docs
Screenshot of features of BeanFacotry and ApplicationContext
A。 bean 工厂和应用程序上下文之间的一个区别是,前者仅在调用 getBean() 方法时实例化 bean,而 ApplicationContext 在容器启动时实例化 Singleton bean,它不会等待 getBean 被调用。
b.
或者
您可以根据您的项目要求使用一个或多个 xml 文件。 因为我在这里使用两个 xml 文件,一个用于服务类的配置详细信息,另一个用于 dao 类。 这里 ClassPathXmlApplicationContext 是 ApplicationContext 的子级。
C。 BeanFactory容器是基本容器,它只能创建对象和注入依赖项。 但是我们无法附加其他服务(例如安全性、事务、消息传递等)来提供我们必须使用 ApplicationContext 容器的所有服务。
d. BeanFactory 不提供对国际化(即 i18n)的支持,但 ApplicationContext 提供对它的支持。
e. BeanFactory Container不支持AutoScanning功能(支持基于Annotation的依赖注入),但ApplicationContext Container支持。
F。 Beanfactory容器直到请求时间才会创建bean对象。 这意味着 Beanfactory 容器会延迟加载 bean。 而ApplicationContext Container仅在加载时创建Singleton bean的对象。 这意味着存在提前加载。
G。 Beanfactory 容器仅支持两个范围(单例和原型)的 bean。 但ApplicationContext容器支持所有的bean范围。
a. One difference between bean factory and application context is that former only instantiate bean when you call getBean() method while ApplicationContext instantiates Singleton bean when the container is started, It doesn't wait for getBean to be called.
b.
or
You can use one or more xml file depending on your project requirement. As I am here using two xml files i.e. one for configuration details for service classes other for dao classes. Here ClassPathXmlApplicationContext is child of ApplicationContext.
c. BeanFactory Container is basic container, it can only create objects and inject Dependencies. But we can’t attach other services like security, transaction, messaging etc. to provide all the services we have to use ApplicationContext Container.
d. BeanFactory doesn't provide support for internationalization i.e. i18n but ApplicationContext provides support for it.
e. BeanFactory Container doesn't support the feature of AutoScanning (Support Annotation based dependency Injection), but ApplicationContext Container supports.
f. Beanfactory Container will not create a bean object until the request time. It means Beanfactory Container loads beans lazily. While ApplicationContext Container creates objects of Singleton bean at the time of loading only. It means there is early loading.
g. Beanfactory Container support only two scopes (singleton & prototype) of the beans. But ApplicationContext Container supports all the beans scope.
我的六美分:
BeanFactory
和ApplicationContext
都是接口,其中ApplicationContext
扩展<代码>BeanFactory。 因此,ApplicationContext
是一个子接口,BeanFactory
是父接口。 换句话说,ApplicationContext
具有BeanFactory
的所有功能,并且具有BeanFactory
中不存在的一些附加功能 >。BeanFactory
按需加载 Bean,即延迟加载,而ApplicationContext
在启动时加载所有 Bean,即急切加载。BeanFactory
不支持注释,而ApplicationContext
支持注释。ApplicationContext
具有BeanFactory
中不存在的附加功能:国际化、事件发布、AOP 功能。BeanFactory
仅支持两个范围 - Singleton 和 Prototype,而ApplicationContext
支持所有 bean范围。BeanFactory
不会自动注册BeanFactoryPostProcessor
和BeanPostProcessor
,而ApplicationContext
会自动注册它们。My six cents:
BeanFactory
andApplicationContext
both are interfaces whereApplicationContext
extendsBeanFactory
. SoApplicationContext
is a child interface andBeanFactory
is the parent interface. In other words,ApplicationContext
has all the features ofBeanFactory
and it has some additional features that are not present inBeanFactory
.BeanFactory
loads beans on-demand that is Lazy Loading whereasApplicationContext
loads all beans at startup that is Eager Loading.BeanFactory
does not support annotations whereasApplicationContext
supports annotations.ApplicationContext
has additional features that are not present inBeanFactory
: Internationalization, Event Publishing, AOP features.BeanFactory
only supports two scopes — Singleton and Prototype whereasApplicationContext
supports all bean scopes.BeanFactory
does not registerBeanFactoryPostProcessor
andBeanPostProcessor
automatically whereasApplicationContext
automatically registers them.请参阅 Spring 文档中的此文档:
http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/beans.html#context-introduction-ctx-vs -bean工厂
5.15.1 BeanFactory 还是 ApplicationContext?
使用 ApplicationContext 除非您有充分的理由不这样做。
因为 ApplicationContext 包含 BeanFactory 的所有功能,所以通常建议使用它而不是 BeanFactory,除了少数情况,例如在 Applet 中,内存消耗可能很关键,并且额外的几 KB 可能会产生影响。 但是,对于大多数典型的企业应用程序和系统,您将需要使用 ApplicationContext。 Spring 2.0 及更高版本大量使用 BeanPostProcessor 扩展点(以实现代理等)。 如果您只使用普通的 BeanFactory,那么大量的支持(例如事务和 AOP)将不会生效,至少在您没有执行一些额外步骤的情况下是这样。 这种情况可能会令人困惑,因为配置实际上没有任何问题。
Refer this doc from 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 BeanFactory or ApplicationContext?
Use an ApplicationContext unless you have a good reason for not doing so.
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 是 BeanFactory 的老大哥,这将是 BeanFactory 提供的所有东西以及许多其他东西。
除了标准的 org.springframework.beans.factory.BeanFactory 生命周期功能之外,ApplicationContext 实现还检测和
调用 ApplicationContextAware bean 以及 ResourceLoaderAware、ApplicationEventPublisherAware 和 MessageSourceAware bean。
ApplicationContext is a big brother of BeanFactory and this would all thing that BeanFactory are provide plus many other things.
In addition to standard org.springframework.beans.factory.BeanFactory lifecycle capabilities, ApplicationContext implementations detect and
invoke ApplicationContextAware beans as well as ResourceLoaderAware, ApplicationEventPublisherAware and MessageSourceAware beans.
在实时场景下,Spring IOC Core容器(BeanFactory)和Advanced J2EE容器(ApplicationContext)的区别如下。
仅当您调用 .getBean( ) 方法,但是 ApplicationContext 为加载时在 spring.xml 中配置的所有 bean(
如果其范围未明确提及为“Prototype”)创建对象spring.xml 文件本身。BeanFactory:(惰性容器,因为仅当您从用户/主类显式调用时,它才为 Bean 创建对象)
<前><代码>/*
* 使用核心容器 - 惰性容器 - 因为它按需创建 bean 对象
*/
//创建资源
资源 r = (资源) new ClassPathResource("com.spring.resources/spring.xml");
//创建BeanFactory
BeanFactory 工厂=new XmlBeanFactory(r);
//获取 POJO 类“HelloWorld.java”的 bean
HelloWorld worldObj1 = (HelloWorld)factory.getBean("test");
ApplicationContext:(渴望容器,因为在加载 spring.xml 文件本身时创建所有单例 bean 的对象)
从技术上讲,建议使用 ApplicationContext,因为在实时应用程序中,bean 对象将在应用程序在服务器本身中启动时创建。 这减少了用户请求的响应时间,因为对象已经可以响应。
In a real-time scenario, the difference between the Spring IOC Core container (BeanFactory) and Advanced J2EE container (ApplicationContext) are as follows.
BeanFactory will create objects for the beans (i.e., for POJO classes) mentioned in the spring.xml file (
<bean></bean>
) only when you call the .getBean() method, but whereas ApplicationContext creates the objects for all the beans (<bean></bean>
if its scope is not explicitly mentioned as "Prototype") configured in the spring.xml while loading the spring.xml file itself.BeanFactory: (Lazy container because it creates the objects for the beans only when you explicitly call from the user/main class)
ApplicationContext: (Eager container because of creating the objects of all singleton beans while loading the spring.xml file itself)
Technically, using ApplicationContext is recommended because in real-time applications, the bean objects will be created while the application is getting started in the server itself. This reduces the response time for the user request as the objects are already available to respond.
我需要解释一下 BeanFactory & 应用程序上下文。
BeanFactory: BeanFactory是访问SpringBean容器的根接口。有bean容器的基本客户端视图。
该接口由保存 bean 定义数量的对象类实现,每个 bean 都由字符串名称唯一标识
根据 Bean 定义,工厂将返回实例,该实例可能是包含对象的实例或单个共享实例。 将返回哪种类型的实例取决于 bean 工厂配置。
通常Bean工厂会加载所有的Bean定义,这些定义存储在配置源中,如XML等。
提供基本支持
BeanFactory 是一个最简单的容器,为依赖注入应用程序上下文
应用程序上下文是 Spring 应用程序中的一个中心接口,它向应用程序提供配置信息。 它实现了 Bean Factory 接口。
应用程序上下文是一个高级容器,它添加了企业特定功能的高级级别,例如从属性文件解析文本消息的能力......等。
ApplicationContext 提供:
用于访问应用程序组件的 Bean 工厂方法。 继承自ListableBeanFactory。
以通用方式加载文件资源的能力。 继承自ResourceLoader接口。
能够向注册的侦听器发布事件。 继承自ApplicationEventPublisher接口。
解析消息的能力,支持国际化。 继承自MessageSource接口。
从父上下文继承。 后代上下文中的定义将始终优先。 例如,这意味着整个 Web 应用程序可以使用单个父上下文,而每个 servlet 都有自己的子上下文,该子上下文独立于任何其他 servlet。
除了标准 BeanFactory 生命周期功能之外,ApplicationContext 实现还检测并调用 ApplicationContextAware bean 以及 ResourceLoaderAware、ApplicationEventPublisherAware 和 MessageSourceAware bean。
I need to explain the BeanFactory & ApplicationContext.
BeanFactory: BeanFactory is root interface for accessing the SpringBean Container.There is basic client view of a bean container.
That interface is implemented by the object class that holds the number of beans definitions, and each uniquely identify by the String name
Depending the Bean definition the factory will return the instance that instance may be the instance of contained object or a single shared instance. Which type of instance will be return depends of bean factory configuration.
Normally Bean factory will load the all the all the beans definition, which stored in the configuration source like XML...etc.
BeanFactory is a simplest container providing the basic support for Dependency Injection
Application Context
Application context is a central interface with in the spring application that provide the configuration information to the application. It implements the Bean Factory Interface.
Application context is an advance container its add advance level of enterprise specific functionality such as ability to resolve the textual message from the property file....etc
An ApplicationContext provides:
Bean factory methods for accessing application components. Inherited from ListableBeanFactory.
The ability to load file resources in a generic fashion. Inherited from the ResourceLoader interface.
The ability to publish events to registered listeners. Inherited from the ApplicationEventPublisher interface.
The ability to resolve messages, supporting internationalization. Inherited from the MessageSource interface.
Inheritance from a parent context. Definitions in a descendant context will always take priority. This means, for example, that a single parent context can be used by an entire web application, while each servlet has its own child context that is independent of that of any other servlet.
In addition to standard BeanFactory lifecycle capabilities, ApplicationContext implementations detect and invoke ApplicationContextAware beans as well as ResourceLoaderAware, ApplicationEventPublisherAware and MessageSourceAware beans.
BeanFactory 表示 Spring 容器,它在运行时调用 getBean() 方法后延迟实例化 bean 对象。
ApplicationContext 表示 spring 框架,它在部署期间急切实例化 bean 对象,而无需或在运行时调用 getBean() 方法之前。
The BeanFactory means spring container which lazily instantiates bean objects after getBean() method is invoked at runtime.
The ApplicationContext means spring framework which eagerly instantiates bean objects during deployment time without or before invoking getBean() method at runtime.
我觉得值得一提的是,从Spring 3开始,如果你想创建一个工厂,你也可以使用
@configuration
注释与正确的@scope
你的工厂应该可见通过 Spring 容器使用 < code>@ComponentScan 注解或 xml 配置
来自 baeldung 的 Spring bean 作用域文章网站
I think it is worth mentioning that since Spring 3, if you want to create a factory, you can also use the
@configuration
annotation combined with the proper@scope
Your factory should be visible by Spring container using the
@ComponentScan
annotation or xml configurationSpring bean scopes article from baeldung site
不要将 BeanFactory 用于非 Web 应用程序,因为它仅支持 Singleton 和 Prototype bean 范围。
虽然 ApplicationContext 容器确实支持所有 bean 范围,所以您应该将它用于 Web 应用程序。
do use BeanFactory for non-web applications because it supports only Singleton and Prototype bean-scopes.
While ApplicationContext container does support all the bean-scopes so you should use it for web applications.
总之:
ApplicationContext 包含 BeanFactory 的所有功能。
一般推荐使用前者。
在某些有限的情况下,例如在移动应用程序中,内存消耗可能很关键。
在这种情况下,使用更轻量级的 BeanFactory 是合理的。 但是,在大多数企业应用程序中,您将需要使用ApplicationContext。
有关更多信息,请参阅我的博客文章:
Spring 中 BeanFactory 和 ApplicationContext 之间的区别– java spring 博客从基础开始
In summary:
The ApplicationContext includes all functionality of the BeanFactory.
It is generally recommended to use the former.
There are some limited situations such as in a Mobile application, where memory consumption might be critical.
In that scenarios, It can be justifiable to use the more lightweight BeanFactory. However, in the most enterprise applications, the ApplicationContext is what you will want to use.
For more, see my blog post:
Difference between BeanFactory and ApplicationContext in Spring – The java spring blog from the basics