Spring high-frequency test questions - what exactly are BeanFactory and Application?

foreword


You and I meet here, all because of stereotyped essays.

I will be looking for an internship in a year, so I want to reserve knowledge in advance, and hope that I will not be tortured to death when I am interviewed. This series of articles will share my experience and knowledge of exploring the Spring framework.

At this point, since you can't escape, let's make it hard.

Here are the questions explored in this article:

  • The difference between BeanFactory and Application?
  • Implementation of BeanFactory and Application?

1. What is the difference between BeanFactory and ApplicationContext?

1. What are they?

As the name suggests, BeanFactory is a bean processing factory whose main responsibility is to instantiate , configure and manage beans , and supports lazy initialization (supports instantiation when the bean is obtained), providing the simplest container function.

ApplicationContext-------Application context is a sub-interface of BeanFactory, derived from BeanFactory. It is a high-level interface that maintains Bean definitions and collaboration relationships between objects, and can provide more enterprise-level functions.

Both are containers in the Spring framework, and ApplicationContext inherits multiple interfaces. Compared with BeanFactory, it has expanded more practical functions. As the core container of Spring, it plays an indispensable function.

We first see the inheritance relationship between the two

image.png

ApplicationtonContext indirectly inherits BeanFactory

At the same time, BeanFactory, as a container of simple functions, has two manifestations.

First , we can know that the getBean method of AbstractApplicationContext in an implementation class of ConfigurableApplicationContext generated by SpringApplication.

image.png

Second , DefaultListableBeanFactorys implements BeanFactory . As an ApplicationContext property, a property of type ConcurrentHashMap is set to save all singleton beans

image.png

traverse the results

 

​edit

2. Difference

As an ancient Factory, BeanFactory provides IOC (inversion of control: the transfer of object control is reversed from the program code itself to the external container. The creation, initialization, and destruction of objects are handed over to the container.) and DI ( Dependency injection) function, but it cannot support spring plug-ins, such as: AOP, Web application and other functions.

When we use BeanFactory to obtain beans, we just instantiate the container, and the beans in the container are not instantiated. When we getBean, the bean object will be instantiated in real time, commonly known as lazy loading

Some common implementation classes of the BeanFactory interface include DefaultListableBeanFactory and XmlBeanFactory .

In addition to providing all the functions of BeanFactory, ApplicationContext also provides more enterprise-level features, such as AOP (aspect-oriented programming), event publishing, internationalization, resource loading, Bean lifecycle management, security, etc. 

  1. EnvironmentCapable integrates Environment's environment  
  2. MessageSource internationalization
  3. ResourcePatternResolver obtains a set of Resource resources through wildcards
  4. ApplicationEventPublisher event publishing and monitoring 

image.png

 Event publishing and monitoring 

image.png

 

image.png

When we use ApplicationContext to get beans, the required beans will be pre-created

2. Implementation of BeanFactory and ApplicationContext?

Implementation of BeanFactory

Create a BeanFactory object --> define the bean (class, scope, initialization, destruction) --> register the bean

——> Add common processors and set comparators for BeanFactory (used to parse annotations, such as @Bean, @Configuration) —> Make post processors work —> Supplement post processors

Note: The first addition of commonly used processors is just adding some post-processors to the BeanFactory, which is just a bean in the BeanFactory, and the connection has not been established. The second is to add the connection between the BeanFactory and the post-processor to tell After each bean of BeanFactory is created, which post-processors are needed.

 
 

scss

copy code

DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); //定义 AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition(Config.class). setScope("singleton").getBeanDefinition(); //注册 beanFactory.registerBeanDefinition("config",beanDefinition); //为BeanFactory提供一些常用处理器 //此外还设置了比较器 AnnotationConfigUtils.registerAnnotationConfigProcessors(beanFactory); //根据一个类型获取多个Bean,使其工作,扩展 beanFactory.getBeansOfType(BeanFactoryPostProcessor.class).values().stream().forEach(beanFactoryPostProcessor -> { System.out.println(beanFactoryPostProcessor); beanFactoryPostProcessor.postProcessBeanFactory(beanFactory); }); System.out.println("<<<<<<<<<<<<<<<<<<<<<<<<<"); //Bean后处理器,对bean生命周期各个阶段提供扩展,告诉bean工厂,创建bean实例的时候需要哪些后处理器 //internalCommonAnnotationProcessor Resource处理器 beanFactory.getBeansOfType(BeanPostProcessor.class). values().stream().sorted(beanFactory.getDependencyComparator()) .forEach(beanPostProcessor -> { System.out.println("beanFactory.getBeansOfType数据如下:"+beanPostProcessor); beanFactory.addBeanPostProcessor(beanPostProcessor); }); for (String beanDefinitionName : beanFactory.getBeanDefinitionNames()) { System.out.println(beanDefinitionName); } //预先创建好Bean,Bean的创建是懒加载 beanFactory.preInstantiateSingletons();

post processor implementation

@Autowried is automatically assembled according to the type. When an interface has two implementation classes and they are both injected into the container, what happens if you use @Autowried to inject dependencies into this interface?

The answer is to report an exception

Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException

Because BeanFactory does not know which implementation class to inject for this interface. The solution is to use @Qualifier or change the name of the interface variable to be consistent with the name of the corresponding implementation class, and the injection can also be successful.

The default in @Resource is also based on the variable name, but if name is added, the priority of name will be higher

Assuming that dependency injection is performed for properties in a class at this time, what will happen if @Resource and @Autowried are added at the same time?

The answer is that the injection was successful

Because they have a priority relationship, and @Autowried has a higher priority than @Resource, so @Autowried will be processed directly and @Resource will be ignored. When some processors are added in the process, a comparator is set. By reading the source code, we know that they are compared with the set value.

This is the processor of @Resource, and the parameter of setOrder in it indicates its numerical value, and then determines its priority.

Implementation of ApplicationContext

Spring provides various types of container implementations for us to choose in different application scenarios——

  • ClassPathXmlApplicationContext (loads XML configuration files from the classpath)
  • AnnotationConfigApplicationContext (configured using Java annotations)
  • FileSystemXmlApplicationContext (loads XML configuration files from the file system)
  • XmlWebApplicationContext ( load context definitions from one or more xml configuration files under the web application, applicable to xml configuration mode)

At the same time, compared with BeanFactory, it saves the post-processor to add supplementary operations.

Guess you like

Origin blog.csdn.net/wdj_yyds/article/details/131897790