spring学习笔记

容器接口

BeanFactory

什么是BeanFactory

1.它是ApplicationContext的父接口

2.它才是Spring的核心容器,主要的ApplicationContext实现都【组合】了它的功能,BeanFactory是ApplicationContext的成员变量

BeanFactory能干啥

1.表面上只有getBean方法

2.实际上,控制反转、基本的依赖注入,制止Bean的生命周期的各种功能,都由它的实现类提供例如DefaultListableBeanFactory,继承关系如下

DefaultListableBeanFactory继承关系图

DefaultListableBeanFactory

DefaultSingletonBeanRegistry

该类有一个如下成员变量
private final Map<String, Object> singletonObjects = new ConcurrentHashMap(256);
是私有的,我们可以通过反射的方式拿到它的成员变量

ApplicationContext有哪些扩展功能

org.springframework.boot.SpringApplication#run(java.lang.Class<?>, java.lang.String…)方法返回org.springframework.context.ConfigurableApplicationContext,我们来看一下他的接口继承关系

ConfigurableApplicationContext继承关系图

可以看出ApplicationContext间接继承了BeanFactory

ApplicationContext对BeanFactory进行了一些扩展,其中主要有(MessageSource、ResourcePatternResolver、ApplicationEventPublisher、EnviromentCapable)

MessageSource

MessageSource提供了处理国际化的能力,国际化字典我们一半存储在resource目录下的messages开头的properties文件

resource示例

1
2
3
ConfigurableApplicationContext context = SpringApplication.run(MarketServerApplication.class);
String hi = context.getMessage("hi", null, Locale.CHINA);
System.out.println(hi);

ResourcePatternResolver

ResourcePatternResolver资源文件的处理能力,如application.properties

1
2
3
4
5
ConfigurableApplicationContext context = SpringApplication.run(MarketServerApplication.class);
Resource[] resources = context.getResources("classpath*:META-INF/spring.factories");
for (Resource resource : resources) {
System.out.println(resource);
}
1
2
3
URL [jar:file:/Users/anakin/develop/mvn-repository/org/springframework/boot/spring-boot/2.3.12.RELEASE/spring-boot-2.3.12.RELEASE.jar!/META-INF/spring.factories]
URL [jar:file:/Users/anakin/develop/mvn-repository/org/springframework/boot/spring-boot-autoconfigure/2.3.12.RELEASE/spring-boot-autoconfigure-2.3.12.RELEASE.jar!/META-INF/spring.factories]
URL [jar:file:/Users/anakin/develop/mvn-repository/org/springframework/spring-beans/5.2.15.RELEASE/spring-beans-5.2.15.RELEASE.jar!/META-INF/spring.factories]

EnviromentCapable

EnviromentCapable提供配置信息查看能力,可以是配置文件,也可以是环境变量(不区分大小写)等。

1
2
System.out.println(context.getEnviroment().getProperty("java_home"));
System.out.println(context.getEnviroment().getProperty("server.port"));

ApplicationEventPublisher

ApplicationEventPublisher提供事件发布的能力

1
2
Event event = new Event();
applicationContext.publishEvent(event);
1
2
3
@EventListener
public void listenEvent(Event event){
}

容器实现

BeanFactory实现的特点

BeanFactory不会主动做的事情

不会主动调用BeanFactory后处理器

不会主动添加Bean后处理器

不会主动初始化单例对象

不会解析BeanFactory,还不会解析${}与#{}

Bean后处理器有排序的逻辑

DefaultListableBeanFactory

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public static void main(String[] args){
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
// bean 的定义(class,scope,初始化,销毁)
AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition(Config.class).setScope("singleton).getBeanDefinition();
// 给BeanFactory添加一些常用的后置处理器(如@Configuration、@Bean等等扩展功能)
AnnotationConfigUtils.registerAnnotationConfigProcessors(beanFactory);
// 执行Bean工厂后置处理器
Map<String, BeanFactoryPostProcessor> beansOfType = beanFactory.getBeansOfType(BeanFactoryPostProcessor.class);
beansOfType.values().stream().forEach(beanFactoryPostProcessor -> beanFactoryPostProcessor.postProcessBeanFactory(context.getBeanFactory()));
// 添加Bean后置处理器与bean工厂的联系(针对Bean生命周期的各个阶段提供扩展,例如@Autowired、@Resource等)
beanFactory.getBeansOfType(BeanPostProcessor.class).values().forEach(beanFactory::addBeanPostProcessor);
// beanFactory默认延迟创建对象,我们可以执行下面的方法提前创建对象
beanFactory.preInstantiateSingletons();

}

以上添加的后置处理器如下(Bean工厂后置处理器及Bean后置处理器都有)

1
2
3
4
5
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory

常见的Bean工厂后置处理器

1
2
3
4
5
6
7
org.springframework.context.annotation.internalConfigurationAnnotationProcessor------>org.springframework.context.annotation.ConfigurationClassPostProcessor@2b27d5d3
org.springframework.context.event.internalEventListenerProcessor------>org.springframework.context.event.EventListenerMethodProcessor@12115c28
propertySourcesPlaceholderConfigurer------>org.springframework.context.support.PropertySourcesPlaceholderConfigurer@cc3fc5c
preserveErrorControllerTargetClassPostProcessor------>org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration$PreserveErrorControllerTargetClassPostProcessor@2aac60b
cn.hutool.extra.spring.SpringUtil------>cn.hutool.extra.spring.SpringUtil@173602c0
org.springframework.cloud.autoconfigure.RefreshAutoConfiguration$RefreshScopeBeanDefinitionEnhancer------>org.springframework.cloud.autoconfigure.RefreshAutoConfiguration$RefreshScopeBeanDefinitionEnhancer@fdeec12
refreshScope------>org.springframework.cloud.context.scope.refresh.RefreshScope@de579ff

常见的Bean后置处理器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
org.springframework.context.annotation.internalAutowiredAnnotationProcessor------>org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor@6fe55fcf
org.springframework.context.annotation.internalCommonAnnotationProcessor------>org.springframework.context.annotation.CommonAnnotationBeanPostProcessor@4d1f6e1c
org.springframework.aop.config.internalAutoProxyCreator------>proxyTargetClass=true; optimize=false; opaque=false; exposeProxy=false; frozen=false
org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor------>org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor@3431cb1f
webServerFactoryCustomizerBeanPostProcessor------>org.springframework.boot.web.server.WebServerFactoryCustomizerBeanPostProcessor@42c9f2cd
errorPageRegistrarBeanPostProcessor------>org.springframework.boot.web.server.ErrorPageRegistrarBeanPostProcessor@797c67c
methodValidationPostProcessor------>proxyTargetClass=true; optimize=false; opaque=false; exposeProxy=false; frozen=false
dataSourceInitializerPostProcessor------>org.springframework.boot.autoconfigure.jdbc.DataSourceInitializerPostProcessor@31ce271c
org.springframework.amqp.rabbit.config.internalRabbitListenerAnnotationProcessor------>org.springframework.amqp.rabbit.annotation.RabbitListenerAnnotationBeanPostProcessor@b1d7b09
healthEndpointGroupsBeanPostProcessor------>org.springframework.boot.actuate.autoconfigure.health.HealthEndpointConfiguration$HealthEndpointGroupsBeanPostProcessor@64faf3d
meterRegistryPostProcessor------>org.springframework.boot.actuate.autoconfigure.metrics.MeterRegistryPostProcessor@3f523dae
rabbitConnectionFactoryMetricsPostProcessor------>org.springframework.boot.actuate.autoconfigure.metrics.amqp.RabbitConnectionFactoryMetricsPostProcessor@7fe40b9f
persistenceExceptionTranslationPostProcessor------>proxyTargetClass=true; optimize=false; opaque=false; exposeProxy=false; frozen=false
projectingArgumentResolverBeanPostProcessor------>org.springframework.data.web.config.ProjectingArgumentResolverRegistrar$ProjectingArgumentResolverBeanPostProcessor@1f41f259
configurationPropertiesBeans------>org.springframework.cloud.context.properties.ConfigurationPropertiesBeans@648c80cb
org.springframework.context.annotation.internalAsyncAnnotationProcessor------>proxyTargetClass=false; optimize=false; opaque=false; exposeProxy=false; frozen=false

一些Bean工厂后置处理器的实现类图

一些Bean后置处理器的实现类图

ApplicationContext的常见实现与特点

ApplicationContext实现关系图

内嵌容器注册DispatcherServlet

如果本文对你有所帮助,请赏我1个铜板买喵粮自己吃,您的支持是我最大的动力!!!