https://www.baeldung.com/spring-beanfactory-vs-applicationcontext

1. Overview

The Spring Framework comes with two IOC containers – BeanFactory and ApplicationContext. The BeanFactory is the most basic version of IOC containers, and the ApplicationContext extends the features of BeanFactory.

Spring框架带有两个IOC容器-BeanFactory和ApplicationContext。 BeanFactory是IOC容器的最基本版本,ApplicationContext扩展了BeanFactory的功能。

In this quick tutorial, we'll understand the significant differences between these two IOC containers with practical examples.

在本快速教程中,我们将通过实际示例了解这两个IOC容器之间的显着差异。

2. Lazy Loading vs. Eager Loading

BeanFactory按需加载bean,而ApplicationContext在启动时加载所有bean。因此,与ApplicationContext相比,BeanFactory是轻量级的。让我们通过一个例子来理解它。

2.1. Lazy Loading With BeanFactory

Let's suppose we have a singleton bean class called Student with one method:

假设我们有一个叫做Student的单例bean类,它带有一个方法:

public class Student {
    public static boolean isBeanInstantiated = false;

    public void postConstruct() {
        setBeanInstantiated(true);
    }

    //standard setters and getters
}

We'll define the postConstruct() method as the init-method in our BeanFactory configuration file, ioc-container-difference-example.xml:

我们将在BeanFactory配置文件 ioc-container-difference-example.xml 中将postConstruct() 方法定义为初始化方法:

<bean id="student" class="com.baeldung.ioccontainer.bean.Student" init-method="postConstruct"/>

Now, let's write a test case that creates a BeanFactory to check if it loads the Student bean:

现在,让我们编写一个测试用例,创建一个 BeanFactory 来检查它是否加载了Student bean:

@Test
public void whenBFInitialized_thenStudentNotInitialized() {
    Resource res = new ClassPathResource("ioc-container-difference-example.xml");
    BeanFactory factory = new XmlBeanFactory(res);

    assertFalse(Student.isBeanInstantiated());
}