我是Spring框架的新手,我一直在摆弄它,并把一些样本应用放在一起,目的是评估Spring MVC在即将到来的公司项目中的使用。到目前为止,我真的很喜欢Spring MVC,它看起来很容易使用,并鼓励你编写对单元测试非常友好的类。

作为练习,我正在为我的一个示例/测试项目编写一个主方法。我不清楚的一件事是BeanFactory和ApplicationContext之间的确切区别——哪个适合在哪些条件下使用?

我知道ApplicationContext扩展了BeanFactory,但是如果我只是编写一个简单的主方法,我是否需要ApplicationContext提供的额外功能呢?ApplicationContext究竟提供了什么样的额外功能?

除了回答“我应该在main()方法中使用哪个”之外,关于在这样的场景中应该使用哪个实现,是否有任何标准或指南?我的main()方法是否应该被编写成依赖于bean/应用程序配置的XML格式——这是一个安全的假设吗,还是我将用户锁定到某个特定的东西?

这个答案在web环境中会改变吗——如果我的任何类需要了解Spring,它们更可能需要ApplicationContext吗?

谢谢你的帮助。我知道很多问题都可以在参考手册中找到答案,但如果没有仔细阅读手册,我很难找到这两个接口的清晰分解以及各自的优缺点。


当前回答

在非web应用程序中使用BeanFactory,因为它只支持单例和原型bean作用域。

而ApplicationContext容器确实支持所有的bean作用域,所以你应该将它用于web应用程序。

其他回答

BeanFactory指的是在运行时调用getBean()方法后延迟实例化bean对象的spring容器。

ApplicationContext指的是spring框架,它在部署期间主动实例化bean对象,而不在运行时调用getBean()方法。

在非web应用程序中使用BeanFactory,因为它只支持单例和原型bean作用域。

而ApplicationContext容器确实支持所有的bean作用域,所以你应该将它用于web应用程序。

在实时场景中,Spring IOC核心容器(BeanFactory)和高级J2EE容器(ApplicationContext)之间的区别如下。

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) /* * 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"); 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.

为了补充Miguel Ping回答的问题,这里是文档中的另一个部分,也回答了这个问题:

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

(将这篇文章发布给未来可能会读到这个问题的春季新手)

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

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.

考虑到这一点,我最初选择BeanFactory用于集成/性能测试,因为我不想加载整个应用程序来测试孤立的bean。但是——如果我说错了,有人会纠正我——BeanFactory不支持类路径XML配置。因此,BeanFactory和ApplicationContext都提供了我想要的关键特性,但两者都没有。

据我所知,文档中关于覆盖默认实例化行为的说明发生在配置中,而且它是每个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);
        }
    }

}