BeanFactory 与 ApplicationContext

发布于 2024-07-07 20:10:08 字数 759 浏览 10 评论 0原文

我对 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(22

赠意 2024-07-14 20:10:08

spring 文档在这方面非常出色: 3.8.1。 BeanFactory 还是 ApplicationContext?
他们有一个比较表,我将发布一个片段:

Bean Factory

  • Bean 实例化/接线

Application Context

  • Bean 实例化/接线
  • 自动 BeanPostProcessor 注册
  • 自动 BeanFactoryPostProcessor 注册
  • 方便的 MessageSource 访问(对于 i18n)
  • ApplicationEvent 发布

因此,如果您需要在应用程序上下文方面呈现的任何点,您应该使用 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

  • Bean instantiation/wiring

Application Context

  • Bean instantiation/wiring
  • Automatic BeanPostProcessor registration
  • Automatic BeanFactoryPostProcessor registration
  • Convenient MessageSource access (for i18n)
  • ApplicationEvent publication

So if you need any of the points presented on the Application Context side, you should use ApplicationContext.

空袭的梦i 2024-07-14 20:10:08

Spring提供了两种IOC容器,一种是XMLBeanFactory,另一种是ApplicationContext

BeanFactoryApplicationContext
注解支持
BeanPostProcessor 注册手动自动
实现XMLBeanFactoryClassPath/FileSystem/WebXmlApplicationContext
国际化
企业服务
ApplicationEvent 发布

在此处输入图像描述

  • FileSystemXmlApplicationContext 通过完整路径加载的 Bean。
  • ClassPathXmlApplicationContext 通过 CLASSPATH 加载的 Bean
  • XMLWebApplicationContextAnnotationConfigWebApplicationContext 通过 Web 应用程序上下文加载的 Bean。
  • AnnotationConfigApplicationContext 从基于注释的配置加载 Spring bean。

例如:

ApplicationContext applicationContext = new AnnotationConfigApplicationContext(BeansConfiguration.class);
  • ApplicationContext 是由 web.xml中定义的 ContextLoaderListenerContextLoaderServlet 初始化的容器ContextLoaderPluginstruts-config.xml 中定义。

注意XmlBeanFactory从 Spring 3.1 开始已弃用,取而代之的是 DefaultListableBeanFactoryXmlBeanDefinitionReader

Spring provides two kinds of IOC container, one is XMLBeanFactory and other is ApplicationContext.

BeanFactoryApplicationContext
Annotation supportNoYes
BeanPostProcessor RegistrationManualAutomatic
ImplementationXMLBeanFactoryClassPath/FileSystem/WebXmlApplicationContext
InternationalizationNoYes
Enterprise servicesNoYes
ApplicationEvent publicationNoYes

enter image description here

  • FileSystemXmlApplicationContext Beans loaded through the full path.
  • ClassPathXmlApplicationContext Beans loaded through the CLASSPATH
  • XMLWebApplicationContext and AnnotationConfigWebApplicationContext beans loaded through the web application context.
  • AnnotationConfigApplicationContext Loading Spring beans from Annotation based configuration.

example:

ApplicationContext applicationContext = new AnnotationConfigApplicationContext(BeansConfiguration.class);
  • ApplicationContext is the container initialized by a ContextLoaderListener or ContextLoaderServlet defined in a web.xml and ContextLoaderPlugin defined in struts-config.xml.

Note: XmlBeanFactory is deprecated as of Spring 3.1 in favor of DefaultListableBeanFactory and XmlBeanDefinitionReader.

本王不退位尔等都是臣 2024-07-14 20:10:08

对我来说,选择 BeanFactory 而不是 ApplicationContext 的主要区别似乎是 ApplicationContext 将预先实例化所有 bean。 来自 Spring 文档

当 bean 实际创建时,Spring 会尽可能晚地设置属性并解决依赖关系。 这意味着,如果创建该对象或其依赖项之一出现问题,则当您请求某个对象时,已正确加载的 Spring 容器稍后会生成异常。 例如,bean 由于属性缺失或无效而引发异常。 某些配置问题的可见性可能会延迟,这就是为什么 ApplicationContext 实现默认预实例化单例 bean 的原因。 在实际需要这些 bean 之前创建这些 bean 需要花费一些前期时间和内存,您会在创建 ApplicationContext 时而不是稍后发现配置问题。 您仍然可以覆盖此默认行为,以便单例 Bean 将延迟初始化,而不是预先实例化。

鉴于此,我最初选择 BeanFactory 来用于集成/性能测试,因为我不想加载整个应用程序来测试隔离的 bean。 然而——如果我错了,有人会纠正我——BeanFactory 不支持classpath XML 配置。 因此,BeanFactoryApplicationContext 各自提供了我想要的关键功能,但两者都没有。

据我所知,文档中有关覆盖默认实例化行为的注释发生在配置中,并且是针对每个 bean 的,因此我不能只在 XML 文件中设置“lazy-init”属性,否则我就坚持维护一个版本用于测试和一个版本用于部署。

我最终所做的是扩展 ClassPathXmlApplicationContext 来延迟加载 bean,以便在测试中使用,如下所示:

public class LazyLoadingXmlApplicationContext extends ClassPathXmlApplicationContext {

    public LazyLoadingXmlApplicationContext(String[] configLocations) {
        super(configLocations);
    }

    /**
     * Upon loading bean definitions, force beans to be lazy-initialized.
     * @see org.springframework.context.support.AbstractXmlApplicationContext#loadBeanDefinitions(org.springframework.beans.factory.xml.XmlBeanDefinitionReader)
     */

    @Override
    protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws IOException {
        super.loadBeanDefinitions(reader);
        for (String name: reader.getBeanFactory().getBeanDefinitionNames()) {
            AbstractBeanDefinition beanDefinition = (AbstractBeanDefinition) reader.getBeanFactory().getBeanDefinition(name);
            beanDefinition.setLazyInit(true);
        }
    }

}

To me, the primary difference to choose BeanFactory over ApplicationContext seems to be that ApplicationContext will pre-instantiate all of the beans. From the Spring docs:

Spring sets properties and resolves dependencies as late as possible, when the bean is actually created. This means that a Spring container which has loaded correctly can later generate an exception when you request an object if there is a problem creating that object or one of its dependencies. For example, the bean throws an exception as a result of a missing or invalid property. This potentially delayed visibility of some configuration issues is why ApplicationContext implementations by default pre-instantiate singleton beans. At the cost of some upfront time and memory to create these beans before they are actually needed, you discover configuration issues when the ApplicationContext is created, not later. You can still override this default behavior so that singleton beans will lazy-initialize, rather than be pre-instantiated.

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 support classpath XML configuration. So BeanFactory and ApplicationContext 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:

public class LazyLoadingXmlApplicationContext extends ClassPathXmlApplicationContext {

    public LazyLoadingXmlApplicationContext(String[] configLocations) {
        super(configLocations);
    }

    /**
     * Upon loading bean definitions, force beans to be lazy-initialized.
     * @see org.springframework.context.support.AbstractXmlApplicationContext#loadBeanDefinitions(org.springframework.beans.factory.xml.XmlBeanDefinitionReader)
     */

    @Override
    protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws IOException {
        super.loadBeanDefinitions(reader);
        for (String name: reader.getBeanFactory().getBeanDefinitionNames()) {
            AbstractBeanDefinition beanDefinition = (AbstractBeanDefinition) reader.getBeanFactory().getBeanDefinition(name);
            beanDefinition.setLazyInit(true);
        }
    }

}
煮茶煮酒煮时光 2024-07-14 20:10:08

要添加 Miguel Ping 的回答,这里是 文档中的另一部分也回答了这个问题:

简短版本:使用 ApplicationContext 除非您有充分的理由不这样做。 对于那些想要更深入地了解上述建议的“但为什么”的人,请继续阅读。

(将此帖子发布给任何可能阅读此问题的未来 Spring 新手)

To add onto what Miguel Ping answered, here is another section from the documentation that answers this as well:

Short version: use an ApplicationContext unless you have a really good reason for not doing so. For those of you that are looking for slightly more depth as to the 'but why' of the above recommendation, keep reading.

(posting this for any future Spring novices who might read this question)

世俗缘 2024-07-14 20:10:08
  1. ApplicationContext 是比 BeanFactory 更优选的方式

  2. < p>在新的 Spring 版本中,BeanFactory 被替换为 ApplicationContext。 但为了向后兼容,BeanFactory 仍然存在

  3. ApplicationContext 扩展了 BeanFactory 并具有以下优点
    • 它支持短信国际化
    • 它支持向已注册的侦听器发布事件
    • 访问网址和文件等资源
  1. ApplicationContext is more preferred way than BeanFactory

  2. In new Spring versions BeanFactory is replaced with ApplicationContext. But still BeanFactory exists for backward compatability

  3. ApplicationContext extends BeanFactory and has the following benefits
    • it supports internationalization for text messages
    • it supports event publication to the registered listeners
    • access to the resources such as URLs and files
绅士风度i 2024-07-14 20:10:08

应用程序上下文:
它加载在 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.

夏花。依旧 2024-07-14 20:10:08

我认为最好始终使用 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.

ゃ懵逼小萝莉 2024-07-14 20:10:08

BeanFactoryApplicationContext 之间的区别如下:

  1. BeanFactory 使用延迟初始化 ApplicationContext 使用急切初始化。 对于 BeanFactory,bean 是在调用 getBeans() 方法时创建的,但对于 ApplicationContext,bean 是在创建 ApplicationContext 对象时预先创建的。
  2. BeanFactory 使用语法显式提供资源对象,但 ApplicationContext 自行创建和管理资源对象。
  3. BeanFactory 不支持国际化ApplicationContext 支持国际化。
  4. BeanFactory 不支持基于注释的依赖项注入,但在 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");

Difference between BeanFactory and ApplicationContext are following:

  1. 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.
  2. BeanFactory explicitly provide a resource object using syntax but ApplicationContext creates and manages resource objects on its own.
  3. BeanFactory doesnt support internatiolization but ApplicationContext supports internationalization.
  4. With BeanFactory annotation based dependency injection is not supported but annotation based dependency injection is supported in ApplicationContext.

Using BeanFactory:

BeanFactory beanfactory = new XMLBeanFactory(new FileSystemResource("spring.xml"));
 Triangle triangle =(Triangle)beanFactory.getBean("triangle");

Using ApplicationContext:

ApplicationContext context = new ClassPathXMLApplicationContext("spring.xml")
Triangle triangle =(Triangle)context.getBean("triangle");
倾`听者〃 2024-07-14 20:10:08

在大多数情况下,除非您需要节省资源(例如在移动应用程序上),否则首选 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.

腹黑女流氓 2024-07-14 20:10:08

通过两种方式创建 spring 容器对象

  1. 基本上我们可以使用 BeanFactory
  2. 。 使用应用程序上下文。

两者都是接口,

使用实现类我们可以为 Spring 容器创建对象,

区别在于

BeanFactory :

  1. 不支持基于 Annotation 的依赖注入。

  2. 不支持 I18N。

  3. 默认支持延迟加载。

  4. 它不允许配置多个配置文件。

例如: BeanFactory context=new XmlBeanFactory(new Resource("applicationContext.xml"));

ApplicationContext

  1. 支持基于注解的依赖注入。-@Autowired、@PreDestroy

  2. 支持 I18N

  3. 默认支持主动加载。

  4. 它允许配置多个配置文件。

例如:
ApplicationContext context=new ClasspathXmlApplicationContext("applicationContext.xml");

Basically we can create spring container object in two ways

  1. using BeanFactory.
  2. using ApplicationContext.

both are the interfaces,

using implementation classes we can create object for spring container

coming to the differences

BeanFactory :

  1. Does not support the Annotation based dependency Injection.

  2. Doesn't Support I18N.

  3. By default its support Lazy loading.

  4. it doesn't allow configure to multiple configuration files.

ex: BeanFactory context=new XmlBeanFactory(new Resource("applicationContext.xml"));

ApplicationContext

  1. Support Annotation based dependency Injection.-@Autowired, @PreDestroy

  2. Support I18N

  3. Its By default support Aggresive loading.

  4. It allow to configure multiple configuration files.

ex:
ApplicationContext context=new ClasspathXmlApplicationContext("applicationContext.xml");

墟烟 2024-07-14 20:10:08

BeanFactoryApplicationContext 都是从 spring IOC 容器中获取 bean 的方法,但仍然存在一些差异。

BeanFactory 是实例化、配置和管理许多 bean 的实际容器。 这些 Bean 通常相互协作,因此它们之间具有依赖关系。 这些依赖关系反映在 BeanFactory 使用的配置数据中。

BeanFactoryApplicationContext都是Java接口,并且ApplicationContext扩展了BeanFactory。 两者都是使用XML配置文件进行配置。 简而言之,BeanFactory 提供基本的控制反转 (IoC) 和依赖注入 (DI) 功能,而 ApplicationContext 提供高级功能。

一个BeanFactory由接口“org.springframework.beans.factory”表示,其中BeanFactory有多种实现。

ClassPathResource resource = new ClassPathResource("appConfig.xml");
XmlBeanFactory factory = new XmlBeanFactory(resource);

区别

  1. BeanFactory在调用getBean()方法时实例化bean,而ApplicationContext在容器启动时实例化Singleton bean,它不会等待getBean() 被调用。

  2. BeanFactory 不提供对国际化的支持,但 ApplicationContext 提供对国际化的支持。

  3. BeanFactoryApplicationContext 之间的另一个区别是能够将事件发布到注册为侦听器的 Bean。

  4. BeanFactory接口的流行实现之一是XMLBeanFactory,而ApplicationContext接口的流行实现之一是ClassPathXmlApplicationContext strong>。

  5. 如果您使用自动装配并使用 BeanFactory,则需要使用 API 注册 AutoWiredBeanPostProcessor,如果您使用 ApplicationContext,则可以在 XML 中配置该 API。强>。 总之,BeanFactory 适合测试和非生产使用,但 ApplicationContext 是功能更丰富的容器实现,应该比 BeanFactory 更受青睐

  6. < 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.

ClassPathResource resource = new ClassPathResource("appConfig.xml");
XmlBeanFactory factory = new XmlBeanFactory(resource);

DIFFERENCE

  1. 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.

  2. BeanFactory doesn't provide support for internationalization but ApplicationContext provides support for it.

  3. Another difference between BeanFactory vs ApplicationContext is ability to publish event to beans that are registered as listener.

  4. One of the popular implementation of BeanFactory interface is XMLBeanFactory while one of the popular implementation of ApplicationContext interface is ClassPathXmlApplicationContext.

  5. 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

  6. BeanFactory by default its support Lazy loading and ApplicationContext by default support Aggresive loading.

柏林苍穹下 2024-07-14 20:10:08

Bean Factory 与应用程序上下文的功能矩阵 源自 spring 文档

在此处输入图像描述

BeanFacotry 和 ApplicationContext 功能的屏幕截图

Feature Matrix of Bean Factory vs Application Context sourced from spring docs

enter image description here

Screenshot of features of BeanFacotry and ApplicationContext

弄潮 2024-07-14 20:10:08

A。 bean 工厂和应用程序上下文之间的一个区别是,前者仅在调用 getBean() 方法时实例化 bean,而 ApplicationContext 在容器启动时实例化 Singleton bean,它不会等待 getBean 被调用。

b.

ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");

或者

ApplicationContext context = new ClassPathXmlApplicationContext{"spring_dao.xml","spring_service.xml};

您可以根据您的项目要求使用一个或多个 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.

ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");

or

ApplicationContext context = new ClassPathXmlApplicationContext{"spring_dao.xml","spring_service.xml};

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.

微凉徒眸意 2024-07-14 20:10:08

我的美分:

  1. BeanFactoryApplicationContext都是接口,其中ApplicationContext扩展<代码>BeanFactory。 因此,ApplicationContext 是一个接口,BeanFactory接口。 换句话说,ApplicationContext 具有 BeanFactory 的所有功能,并且具有 BeanFactory 中不存在的一些附加功能 >。
  2. BeanFactory 按需加载 Bean,即延迟加载,而 ApplicationContext 在启动时加载所有 Bean,即急切加载
  3. BeanFactory 不支持注释,而ApplicationContext 支持注释。
  4. ApplicationContext 具有 BeanFactory 中不存在的附加功能国际化、事件发布、AOP 功能
  5. BeanFactory 仅支持两个范围 - SingletonPrototype,而 ApplicationContext 支持所有 bean范围。
  6. BeanFactory 不会自动注册 BeanFactoryPostProcessorBeanPostProcessor,而 ApplicationContext 会自动注册它们。

My six cents:

  1. BeanFactory and ApplicationContext both are interfaces where ApplicationContext extends BeanFactory. So ApplicationContext is a child interface and BeanFactory is the parent interface. In other words, ApplicationContext has all the features of BeanFactory and it has some additional features that are not present in BeanFactory.
  2. BeanFactory loads beans on-demand that is Lazy Loading whereas ApplicationContext loads all beans at startup that is Eager Loading.
  3. BeanFactory does not support annotations whereas ApplicationContext supports annotations.
  4. ApplicationContext has additional features that are not present in BeanFactory: Internationalization, Event Publishing, AOP features.
  5. BeanFactory only supports two scopes — Singleton and Prototype whereas ApplicationContext supports all bean scopes.
  6. BeanFactory does not register BeanFactoryPostProcessor and BeanPostProcessor automatically whereas ApplicationContext automatically registers them.
〗斷ホ乔殘χμё〖 2024-07-14 20:10:08

请参阅 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.

调妓 2024-07-14 20:10:08

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.

撕心裂肺的伤痛 2024-07-14 20:10:08

在实时场景下,Spring IOC Core容器(BeanFactory)和Advanced J2EE容器(ApplicationContext)的区别如下。

  1. 仅当您调用 .getBean( ) 方法,但是 ApplicationContext 为加载时在 spring.xml 中配置的所有 bean( 如果其范围未明确提及为“Prototype”)创建对象spring.xml 文件本身。

  2. 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 context = new ClassPathXmlApplicationContext("com/ioc/constructorDI/resources/spring.xml"); 
      
  3. 从技术上讲,建议使用 ApplicationContext,因为在实时应用程序中,bean 对象将在应用程序在服务器本身中启动时创建。 这减少了用户请求的响应时间,因为对象已经可以响应。

In a real-time scenario, the difference between the Spring IOC Core container (BeanFactory) and Advanced J2EE container (ApplicationContext) are as follows.

  1. 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.

  2. BeanFactory: (Lazy container because it creates the objects for the beans only when you explicitly call from the user/main class)

    /*
     * Using core Container - Lazy container - Because it creates the bean objects On-Demand
     */
    //creating a resource
    Resource r = (Resource) new ClassPathResource("com.spring.resources/spring.xml");
    //creating BeanFactory 
    BeanFactory factory=new XmlBeanFactory(r);
    
    //Getting the bean for the POJO class "HelloWorld.java"
    HelloWorld worldObj1 = (HelloWorld) factory.getBean("test");
    

    ApplicationContext: (Eager container because of creating the objects of all singleton beans while loading the spring.xml file itself)

    ApplicationContext context = new ClassPathXmlApplicationContext("com/ioc/constructorDI/resources/spring.xml");
    
  3. 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.

悸初 2024-07-14 20:10:08

我需要解释一下 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.

極樂鬼 2024-07-14 20:10:08

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.

梦情居士 2024-07-14 20:10:08

我觉得值得一提的是,从Spring 3开始,如果你想创建一个工厂,你也可以使用 @configuration 注释与正确的 @scope

@Configuration
public class MyFactory {

    @Bean
    @Scope("prototype")
    public MyClass create() {
        return new MyClass();
    }
}

你的工厂应该可见通过 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

@Configuration
public class MyFactory {

    @Bean
    @Scope("prototype")
    public MyClass create() {
        return new MyClass();
    }
}

Your factory should be visible by Spring container using the @ComponentScan annotation or xml configuration

Spring bean scopes article from baeldung site

零崎曲识 2024-07-14 20:10:08

不要将 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.

戏蝶舞 2024-07-14 20:10:08

总之:

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文