In-depth understanding of the difference between BeanFactory and ApplicationContext

BeanFactory and ApplicationContext interface and its subclass diagram

insert image description here
This is a part of the relationship class diagram of Spring. From this class diagram, we can roughly see the relationship between BeanFactory and ApplicationContext. BeanFactory is the base class of ApplicationContext, and ApplicationContext has all the functions of BeanFactory. Not only that, but ApplicationContext also expands some Function, it adds many advanced container features on the basis of the simple IOC container of BeanFactory by inheriting MessageSource, ResourceLoader and other interfaces.

BeanFactory

BeanFactory source code

public interface BeanFactory {
    
    
    // 根据指定名字获取IOC容器管理的Bean
    Object getBean(String name) throws BeansException;
    // 根据指定名字获取IOC指定的Bean, 并且对Bean的类型进行检查
    <T> T getBean(String name, Class<T> requiredType) throws BeansException;
    Object getBean(String name, Object... args) throws BeansException;
    // 根据类型获取IOC容器管理的Bean
    <T> T getBean(Class<T> requiredType) throws BeansException;
    <T> T getBean(Class<T> requiredType, Object... args) throws BeansException;
    <T> ObjectProvider<T> getBeanProvider(Class<T> requiredType);
    <T> ObjectProvider<T> getBeanProvider(ResolvableType requiredType);
    // 判断容器是否包含指定名字的Bean
    boolean containsBean(String name);
    // 判断指定名字的Bean是否是Singeton(单例)类型
    boolean isSingleton(String name) throws NoSuchBeanDefinitionException;
    // 判断指定名字的Bean是否是Prototype(多例)类型
    boolean isPrototype(String name) throws NoSuchBeanDefinitionException;
    boolean isTypeMatch(String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException;
    // 查询指定名字的Bean的Class类型是否是特定的Class类型.
    boolean isTypeMatch(String name, Class<?> typeToMatch) throws NoSuchBeanDefinitionException;
    // 查询指定名字的Bean的Class类型
    @Nullable
    Class<?> getType(String name) throws NoSuchBeanDefinitionException;
    // 查询指定名字的Bean的Class类型
    @Nullable
    Class<?> getType(String name) throws NoSuchBeanDefinitionException;
    @Nullable
    Class<?> getType(String name, boolean allowFactoryBeanInit) throws NoSuchBeanDefinitionException;
    @Nullable
    Class<?> getType(String name, boolean allowFactoryBeanInit) throws NoSuchBeanDefinitionException;
    // 查询指定名字的Bean的所有别名, 这些别名都是用户在BeanDefinition中定义的
    String[] getAliases(String name);

It can be seen that what is defined here is only a series of interface methods, which provide usage specifications for the IOC container. On this basis, Spring also provides a series of containers conforming to the IOC container interface for developers to use. We take the implementation of XmlBeanFactory as an example to illustrate the design principle of simple IOC.

The related class diagram of XmlBeanFactory is as follows
insert image description here
Compared with ApplicationContext, there is a very obvious feature, that is, XmlBeanFactory only provides the most basic IOC container functions.

XmlBeanFactory source code

@Deprecated
@SuppressWarnings({
    
    "serial", "all"})
public class XmlBeanFactory extends DefaultListableBeanFactory {
    
    
    // BeanDefinition读取器
    private final XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this);

    public XmlBeanFactory(Resource resource) throws BeansException {
    
    
        this(resource, null);
    }

    public XmlBeanFactory(Resource resource, BeanFactory parentBeanFactory) throws BeansException {
    
    
        super(parentBeanFactory);
        // 载入BeanDefinition
        this.reader.loadBeanDefinitions(resource);
    }

}

As you can see, to use XmlBeanFactory, we need to pass in the Resource object, which is the BeanDefinition resource, which is the xml file we usually write. The BeanDefinition reader XmlBeanDefinitionReader will automatically load our BeanDefinition into the IOC container for our use.

Let's use XmlBeanFactory:

@Test
    public void test2 () {
    
    
	ClassPathResource classPathResource = new ClassPathResource("application.xml");
	XmlBeanFactory xmlBeanFactory = new XmlBeanFactory(classPathResource);
	Object user = xmlBeanFactory.getBean("user");
	System.out.println(user);
    }

ApplicationContext

We discuss the use of ApplicationContext with ClassPathXmlApplicationContext

ClassPathXmlApplicationContext class diagram

insert image description here
It can be seen from the class diagram that in addition to providing basic BeanFactory functions, ApplicationContext also provides users with the following additional services, which can make users more convenient to use.

  • Supports different information sources. ApplicationContext extends the MessageSource interface. The extension functions of these information sources can support the realization of internationalization and provide services for the development of multi-language versions of applications
  • Access resources. This feature is reflected in the support for ResourceLoader and Resource, so that we can get BeanDefinition resources from different places.

Use of ClassPathXmlApplicationContext

  @Test
    public void test3 () {
    
    
        ApplicationContext applicationContext = new FileSystemXmlApplicationContext("application.xml");
        Object user = applicationContext.getBean("user");
        System.out.println(user);
    }

Summarize:

BeanFactory
BeanFactory is the original interface of spring. The implementation class function for the original structure is relatively simple. The container implemented by the BeanFactory interface is characterized by creating an object every time an object is obtained.

ApplicationContext
inherits the BeanFactory interface, has all the functions of BeanFactory, and extends many advanced features, and creates all objects every time the container starts.

The method of creating ApplicationContext:
load the configuration file under the class path: ClassPathXmlApplicationContext (“applicationContext.xml”);
load the configuration file from the absolute path of the hard disk: FileSystemXmlApplicationContext (“d:/xxx/yyy/xxx”);

Conclusion
The early computer performance was low and the memory was small, so the capacity of the spring container was insufficient. All objects could not be created and placed in the container, so BeanFactory was used. When an object was needed, it was created again. With the improvement of computer hardware With the development, the memory is getting bigger and bigger, so the spring framework introduces the ApplicationContext, creates all the objects, puts them in the container, and which object to use can be obtained from the container.

BeanFactory and ApplicationContext (details)

  • The Bean factory (com.springframework.beans.factory.BeanFactory) is the core interface of the Spring framework, which provides an advanced IoC configuration mechanism.
  • The application context (com.springframework.context.ApplicationContext) is built on top of the BeanFactory.

In almost all applications, we use ApplicationContext directly instead of the underlying BeanFactory.

1. BeanFactory class architecture

BeanFactory : The interface is located at the top of the class structure tree. Its main method is getBean(StringbeanName), which returns a Bean with a specific name from the container. The functions of BeanFactory are continuously expanded through other interfaces.

ListableBeanFactory : This interface defines several methods for accessing the basic information of beans in the container, such as checking the number of beans, obtaining the configuration name of a certain type of bean, checking whether a certain bean is included in the container, etc.;

HierarchicalBeanFactory : the interface of the parent-child cascading IoC container, and the child container can access the parent container through the interface method;

ConfigurableBeanFactory : It is an important interface that enhances the customizability of the IoC container. It defines methods such as setting class loaders, property editors, container initialization post-processors, etc.;

AutowireCapableBeanFactory : Defines the method of automatically assembling the Bean in the container according to certain rules (such as matching by name, matching by type, etc.);

SingletonBeanRegistry : defines a method that allows a single-instance bean to be registered to the container during runtime;

BeanDefinitionRegistry : Each node element in the Spring configuration file is represented by a BeanDefinition object in the Spring container, which describes the configuration information of the Bean. The BeanDefinitionRegistry interface provides a method to manually register the BeanDefinition object with the container.

2. Class Architecture of ApplicationContext

ApplicationContext is derived from BeanFactory and provides more functions for practical applications. In BeanFactory, many functions need to be implemented programmatically, but in ApplicationContext it can be implemented through configuration.
The main implementation classes of ApplicationContext are ClassPathXmlApplicationContext and FileSystemXmlApplicationContext. The former loads configuration files from the class path by default, and the latter loads configuration files from the file system by default.

The core interfaces include:
ApplicationEventPublisher : Let the container have the function of publishing application context events, including container startup events, shutdown events, etc. Beans that implement the ApplicationListener event monitoring interface can receive container events and respond to the events. In the ApplicationContext abstract implementation class AbstractApplicationContext, we can find that there is an ApplicationEventMulticaster, which is responsible for saving all listeners, so as to notify these event listeners when the container generates context events.

MessageSource : Provide the application with the function of i18n internationalized message access;

ResourcePatternResolver : All ApplicationContext implementation classes implement a function similar to PathMatchingResourcePatternResolver, which can load Spring configuration files through prefixed Ant-style resource file paths.

LifeCycle : This interface is added by Spring 2.0. This interface provides two methods of start() and stop(), which are mainly used to control the asynchronous processing process. In specific use, this interface is implemented by ApplicationContext and specific beans at the same time, and ApplicationContext will pass the start/stop information to all beans that implement this interface in the container to achieve management and control of JMX, task scheduling and other purposes.

ConfigurableApplicationContext extends ApplicationContext, and it adds two main methods: refresh() and close(), allowing ApplicationContext to have the ability to start, refresh and close the application context. When the application context is closed, call refresh() to start the application context. In the already started state, call refresh() to clear the cache and reload configuration information, and call close() to close the application context. These interface methods bring convenience to the control and management of containers.

Code example:

ApplicationContext ctx =new ClassPathXmlApplicationContext("com/baobaotao/context/beans.xml");
ApplicationContext ctx =new FileSystemXmlApplicationContext("com/baobaotao/context/beans.xml");
ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[]{
    
    "conf/beans1.xml","conf/beans2.xml"});

There is a major difference between the initialization of ApplicationContext and BeanFactory: BeanFactory does not instantiate beans when initializing the container, and does not instantiate the target bean until the first time a bean is accessed; while ApplicationContext instantiates all singletons when initializing the application context. instance of the bean.

Guess you like

Origin blog.csdn.net/2301_77444674/article/details/131863420