AutowireCapableBeanFactory/README.md接口源码分析

master
xuchengsheng 2023-11-27 17:03:49 +08:00
parent b2f6dfa19c
commit ccf6b84d83
3 changed files with 171 additions and 24 deletions

View File

@ -71,6 +71,7 @@
- [`ResourcePatternResolver`](spring-resources/spring-resource-resourcePatternResolver/README.md):资源模式解析接口,用于灵活加载应用中的多种资源。<img src="https://img.shields.io/badge/Level-%E7%AE%80%E5%8D%95-0099ff"></img>
- [`DocumentLoader`](spring-resources/spring-resource-documentLoader/README.md)XML文档加载解析核心接口支持后台自动配置Spring应用。<img src="https://img.shields.io/badge/Level-%E7%AE%80%E5%8D%95-0099ff"></img>
- 元数据与过滤
- [`MetadataReader`](spring-metadata/spring-metadata-metadataReader/README.md)类元数据获取核心支持组件扫描、条件化注解、AOP等高级功能。<img src="https://img.shields.io/badge/Level-%E7%AE%80%E5%8D%95-0099ff"></img>
@ -80,6 +81,7 @@
- [`TypeFilter`](spring-metadata/spring-metadata-typeFilter/README.md):组件扫描时自定义类筛选,支持复杂条件和精确过滤。<img src="https://img.shields.io/badge/Level-%E7%AE%80%E5%8D%95-0099ff"></img>
- [`Condition`](spring-metadata/spring-metadata-condition/README.md)条件判断决定Bean创建和配置的灵活机制。<img src="https://img.shields.io/badge/Level-%E7%AE%80%E5%8D%95-0099ff"></img>
- Bean定义与注册
- [`BeanDefinition`](spring-beans/spring-bean-beanDefinition/README.md)详细描述Bean支持依赖注入、AOP、作用域控制等核心功能。<img src="https://img.shields.io/badge/Level-%E7%AE%80%E5%8D%95-0099ff"></img>
@ -87,6 +89,7 @@
- [`BeanDefinitionHolder`](spring-beans/spring-bean-beanDefinitionHolder/README.md)管理和操作BeanDefinition的关键类。<img src="https://img.shields.io/badge/Level-%E7%AE%80%E5%8D%95-0099ff"></img>
- [`BeanDefinitionRegistry`](spring-beans/spring-bean-beanDefinitionRegistry/README.md)Bean定义注册管理关键接口处理Bean元数据。<img src="https://img.shields.io/badge/Level-%E7%AE%80%E5%8D%95-0099ff"></img>
- Bean定义读取与扫描
- [`XmlBeanDefinitionReader`](spring-beans/spring-bean-xmlBeanDefinitionReader/README.md)加载解析XML配置构建IOC容器注册Bean定义。<img src="https://img.shields.io/badge/Level-%E4%B8%80%E8%88%AC-%23FF6347"></img>
@ -115,6 +118,7 @@
- `ImportSelector`:运行时动态导入配置类,实现条件选择和灵活配置。<img src="https://img.shields.io/badge/%E5%8D%B3%E5%B0%86%E6%9B%B4%E6%96%B0-339933"></img>
- `DeferredImportSelector`:运行时动态导入配置,支持条件选择和按组别延迟加载。<img src="https://img.shields.io/badge/%E5%8D%B3%E5%B0%86%E6%9B%B4%E6%96%B0-339933"></img>
- Bean工厂
- `BeanFactory`Spring的核心接口提供对Bean的配置、创建、管理的基本功能。<img src="https://img.shields.io/badge/%E5%8D%B3%E5%B0%86%E6%9B%B4%E6%96%B0-339933"></img>
@ -124,11 +128,16 @@
- `HierarchicalBeanFactory`支持父子容器关系实现Bean定义的层次结构。<img src="https://img.shields.io/badge/%E5%8D%B3%E5%B0%86%E6%9B%B4%E6%96%B0-339933"></img>
- `ConfigurableBeanFactory`提供对BeanFactory配置的扩展如属性编辑器、作用域等。<img src="https://img.shields.io/badge/%E5%8D%B3%E5%B0%86%E6%9B%B4%E6%96%B0-339933"></img>
+ [`AutowireCapableBeanFactory`](spring-factory/spring-factory-autowireCapableBeanFactory/README.md)Bean创建、初始化、注入、销毁的核心功能接口。
+ `ConfigurableListableBeanFactory`支持配置和列表操作的可配置Bean工厂接口。<img src="https://img.shields.io/badge/%E5%8D%B3%E5%B0%86%E6%9B%B4%E6%96%B0-339933"></img>
- 基于Java的配置
- `ConfigurationClassPostProcessor`:处理@Configuration注解关键容器启动后置处理器。<img src="https://img.shields.io/badge/%E5%8D%B3%E5%B0%86%E6%9B%B4%E6%96%B0-339933"></img>
- `ConfigurationClassParser`:解析@Configuration提取Config信息支持@Bean和条件化配置。<img src="https://img.shields.io/badge/%E5%8D%B3%E5%B0%86%E6%9B%B4%E6%96%B0-339933"></img>
- 容器上下文
- [`ClassPathXmlApplicationContext`](spring-context/spring-context-classPathXmlApplicationContext/README.md)类路径classpath加载 XML 配置文件的上下文。<img src="https://img.shields.io/badge/Level-%E7%AE%80%E5%8D%95-0099ff"></img>
@ -136,6 +145,7 @@
- [`AnnotationConfigApplicationContext`](spring-context/spring-context-annotationConfigApplicationContext/README.md):注解配置类中加载配置信息的上下文。<img src="https://img.shields.io/badge/Level-%E7%AE%80%E5%8D%95-0099ff"></img>
- `GenericApplicationContext`支持多种配置方式XML、注解、手动注册的上下文。<img src="https://img.shields.io/badge/%E5%8D%B3%E5%B0%86%E6%9B%B4%E6%96%B0-339933"></img>
- Bean生命周期
- [`Bean的定义注册过程`](spring-core/spring-core-registerBeanDefinition)加载与解析配置文件注册解析Bean定义类名、作用域、属性等。<img src="https://img.shields.io/badge/Level-%E4%B8%80%E8%88%AC-%23FF8C69"></img>
@ -145,6 +155,7 @@
- [`Bean的依赖解析过程`](spring-core/spring-core-resolveDependency/README.md):声明依赖,查找依赖,注入依赖,处理循环依赖,延迟依赖解析。<img src="https://img.shields.io/badge/Level-%E5%9B%B0%E9%9A%BE-%23FF3030"></img>
- [`Bean的销毁过程`](spring-core/spring-core-destroyBean/README.md)销毁方法调用接口回调后处理清理通知触发GC回收资源。<img src="https://img.shields.io/badge/Level-%E5%9B%B0%E9%9A%BE-%23FF3030"></img>
- Bean初始化与扩展点
- [`InitializingBean`](spring-interface/spring-interface-initializingBean/README.md)提供Bean初始化时执行自定义逻辑的接口。<img src="https://img.shields.io/badge/Level-%E4%B8%80%E8%88%AC-%23FF8C69"></img>
@ -166,6 +177,7 @@
- [`SmartInstantiationAwareBeanPostProcessor`](spring-interface/spring-interface-smartInstantiationAwareBeanPostProcessor/README.md):提供更智能的实例化控制。<img src="https://img.shields.io/badge/Level-%E4%B8%80%E8%88%AC-%23FF8C69"></img>
- [`SmartInitializingSingleton`](spring-interface/spring-interface-smartInitializingSingleton/README.md)在所有单例Bean初始化完成后执行自定义逻辑。<img src="https://img.shields.io/badge/Level-%E4%B8%80%E8%88%AC-%23FF8C69"></img>
- Aware接口系列
- [`BeanNameAware`](spring-aware/spring-aware-beanNameAware/README.md)让Bean获取自身在容器中的名字。<img src="https://img.shields.io/badge/Level-%E4%B8%80%E8%88%AC-%23FF8C69"></img>
@ -189,6 +201,7 @@
- [`ApplicationContextAware`](spring-aware/spring-aware-applicationContextAware/README.md)允许Bean获取应用程序上下文。<img src="https://img.shields.io/badge/Level-%E4%B8%80%E8%88%AC-%23FF8C69"></img>
- [`ImportAware`](spring-aware/spring-aware-importAware/README.md):允许被导入的配置类获取导入它的类的信息。<img src="https://img.shields.io/badge/Level-%E4%B8%80%E8%88%AC-%23FF8C69"></img>
- 核心注解
- [`@Configuration`](spring-annotation/spring-annotation-configuration/README.md)声明类为配置类定义Bean和Bean之间的依赖关系。<img src="https://img.shields.io/badge/Level-%E5%9B%B0%E9%9A%BE-%23FF3030"></img>
@ -220,6 +233,7 @@
- `@Indexed` 标记Bean用于索引。<img src="https://img.shields.io/badge/%E5%8D%B3%E5%B0%86%E6%9B%B4%E6%96%B0-339933"></img><img src="https://img.shields.io/badge/Level-%E4%B8%80%E8%88%AC-%23FF8C69"></img>
- `@Order`指定Bean的加载顺序。<img src="https://img.shields.io/badge/%E5%8D%B3%E5%B0%86%E6%9B%B4%E6%96%B0-339933"></img><img src="https://img.shields.io/badge/Level-%E4%B8%80%E8%88%AC-%23FF8C69"></img>
- JSR规范
- [`@Inject`](spring-jsr/spring-jsr330-inject/README.md)JSR-330标准的依赖注入注解。<img src="https://img.shields.io/badge/Level-%E4%B8%80%E8%88%AC-%23FF8C69"></img>

View File

@ -1,5 +1,24 @@
## AutowireCapableBeanFactory
- [AutowireCapableBeanFactory](#autowirecapablebeanfactory)
- [一、基本信息](#一基本信息)
- [二、基本描述](#二基本描述)
- [三、主要功能](#三主要功能)
- [四、接口源码](#四接口源码)
- [五、主要实现](#五主要实现)
- [五、最佳实践](#五最佳实践)
- [createBean](#createbean)
- [configureBean](#configurebean)
- [autowireBean](#autowirebean)
- [autowire](#autowire)
- [autowireBeanProperties](#autowirebeanproperties)
- [applyBeanPropertyValues](#applybeanpropertyvalues)
- [initializeBean](#initializebean)
- [destroyBean](#destroybean)
- [resolveDependency](#resolvedependency)
- [常见问题](#常见问题)
### 一、基本信息
✒️ **作者** - Lex 📝 **博客** - [掘金](https://juejin.cn/user/4251135018533068/posts) 📚 **源码地址** - [github](https://github.com/xuchengsheng/spring-reading)
@ -336,6 +355,30 @@ public interface AutowireCapableBeanFactory extends BeanFactory {
}
```
### 五、主要实现
+ `AbstractAutowireCapableBeanFactory`
+ `AbstractAutowireCapableBeanFactory`是`AutowireCapableBeanFactory`接口的抽象实现为Spring框架提供了核心的Bean创建、初始化和销毁功能。它实现了`createBean`方法支持对Bean的依赖注入、属性值应用、后置处理器的应用以及初始化和销毁阶段的生命周期管理。
~~~mermaid
classDiagram
direction BT
class ResourceLoader {
<<interface>>
}
class ResourcePatternResolver {
<<interface>>
}
class PathMatchingResourcePatternResolver {
}
ResourcePatternResolver --|> ResourceLoader
PathMatchingResourcePatternResolver ..|> ResourcePatternResolver
~~~
### 五、最佳实践
使用`AnnotationConfigApplicationContext`创建了Spring应用程序上下文手动注册了一个后置处理器`MyBeanPostProcessor`与一个单例Bean`MyRepository`),最后获取了`AutowireCapableBeanFactory`。
@ -519,3 +562,116 @@ private static void autowireBeanProperties(AutowireCapableBeanFactory beanFactor
调用autowireBeanProperties后,MyService = MyService{myRepository=com.xcs.spring.repository.MyRepository@4145bad8, javaHome='D:\install\jdk-11'}
```
#### applyBeanPropertyValues
使用`AutowireCapableBeanFactory`的`applyBeanPropertyValues`方法,手动为`MyService`类型的Bean配置自定义属性值。首先创建了一个`PropertyValue`实例,表示要设置的属性名为"javaHome",属性值为"这里是我自定义的javaHome路径配置"。接着,通过`MutablePropertyValues`构建了属性值的集合,并将之前创建的`PropertyValue`添加到集合中。然后,创建了一个`RootBeanDefinition`并将属性值集合设置到该Bean定义中。最后通过`registerBeanDefinition`方法注册了一个名为 "myService" 的Bean定义。在调用`applyBeanPropertyValues`方法之前,创建了一个新的`MyService`实例,并输出了其初始状态。然后,调用`applyBeanPropertyValues`方法后,输出了`applyBeanPropertyValues`后的`MyService`实例信息,观察是否成功应用了自定义的属性值。
```java
private static void applyBeanPropertyValues(AutowireCapableBeanFactory beanFactory) {
PropertyValue propertyValue = new PropertyValue("javaHome", "这里是我自定义的javaHome路径配置");
MutablePropertyValues propertyValues = new MutablePropertyValues();
propertyValues.addPropertyValue(propertyValue);
RootBeanDefinition rootBeanDefinition = new RootBeanDefinition(MyService.class);
rootBeanDefinition.setPropertyValues(propertyValues);
// 配置一个RootBeanDefinition
((DefaultListableBeanFactory) beanFactory).registerBeanDefinition("myService", rootBeanDefinition);
MyService myService = new MyService();
System.out.println("调用applyBeanPropertyValues前,MyService = " + myService);
beanFactory.applyBeanPropertyValues(myService, "myService");
System.out.println("调用applyBeanPropertyValues后,MyService = " + myService);
}
```
运行结果发现,调用`applyBeanPropertyValues`方法后,并没有触发`BeanNameAware`接口中的`setBeanName`方法、`InitializingBean`接口中的`afterPropertiesSet`方法,以及自定义的`MyBeanPostProcessor`后置处理器的相应回调方法。这是因为`applyBeanPropertyValues`方法主要专注于属性值的应用而不涉及完整的Bean初始化和生命周期管理。最终的运行结果显示`myRepository`属性为null表明`applyBeanPropertyValues`方法并没有进行依赖注入。
```java
调用applyBeanPropertyValues前,MyService = MyService{myRepository=null, javaHome='null'}
调用applyBeanPropertyValues后,MyService = MyService{myRepository=null, javaHome='这里是我自定义的javaHome路径配置'}
```
#### initializeBean
使用`AutowireCapableBeanFactory`的`initializeBean`方法,手动初始化`MyService`类型的Bean。首先创建了一个新的`MyService`实例,并输出了其初始状态。然后,通过`initializeBean`方法对该实例进行初始化指定了Bean的名称为 "myService"。在调用方法之后,输出了`initializeBean`后的`MyService`实例信息,观察是否成功进行了初始化。
```java
private static void initializeBean(AutowireCapableBeanFactory beanFactory) {
MyService myService = new MyService();
System.out.println("调用initializeBean前,MyService = " + myService);
beanFactory.initializeBean(myService, "myService");
System.out.println("调用initializeBean前,MyService = " + myService);
}
```
运行结果发现,`myRepository`和`javaHome`的值都显示为`null`,这是因为在调用`initializeBean`方法时,并没有提供属性值的注入。`initializeBean`方法主要用于手动触发Bean的初始化阶段包括调用`afterPropertiesSet`方法和应用Bean后置处理器但它并不负责属性的注入。
```java
调用initializeBean前,MyService = MyService{myRepository=null, javaHome='null'}
MyService.setBeanName方法被调用了
MyBeanPostProcessor#postProcessBeforeInitialization方法被调用了,Bean名称 = myService
MyService.afterPropertiesSet方法被调用了
MyBeanPostProcessor#postProcessBeforeInitialization方法被调用了,Bean名称 = myService
调用initializeBean前,MyService = MyService{myRepository=null, javaHome='null'}
```
#### destroyBean
使用`AutowireCapableBeanFactory`的`destroyBean`方法手动销毁destroy一个`MyService`类型的Bean实例。通过传递新创建的`MyService`实例作为参数,调用了`destroyBean`方法。
```java
private static void destroyBean(AutowireCapableBeanFactory beanFactory) {
beanFactory.destroyBean(new MyService());
}
```
运行结果发现,在调用`destroyBean`方法后,`MyService`实例的销毁方法 `destroy` 被成功调用。这表明`destroyBean`方法有效地触发了Bean的销毁阶段执行了实现了`DisposableBean`接口的`destroy`方法。
```java
MyService.destroy方法被调用了
```
#### resolveDependency
使用`AutowireCapableBeanFactory`的`resolveDependency`方法,手动解析一个依赖关系。通过创建一个`DependencyDescriptor`对象,表示`MyService`类中的`myRepository`属性,然后调用`resolveDependency`方法,尝试解析这个依赖关系。最后,输出解析得到的依赖对象。
```java
private static void resolveDependency(AutowireCapableBeanFactory beanFactory) {
try {
DependencyDescriptor dependencyDescriptor = new DependencyDescriptor(MyService.class.getDeclaredField("myRepository"), false);
Object resolveDependency = beanFactory.resolveDependency(dependencyDescriptor, "myRepository");
System.out.println("resolveDependency = " + resolveDependency);
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
```
运行结果发现,通过调用`resolveDependency`方法成功解析了依赖关系,将`myRepository`属性的依赖解析为`MyRepository`的实例。
```java
resolveDependency = com.xcs.spring.repository.MyRepository@37654521
```
### 常见问题
1. **createBean() 和 configureBean()**
- `createBean()` 用于创建Bean的实例即进行Bean的实例化。它是Bean创建过程中的第一步。
- `configureBean()` 则是在Bean实例创建之后进行进一步的配置如应用BeanPostProcessors等。这是在Bean实例化后、初始化之前的阶段。
2. **autowireBean() 和 autowire()**
- `autowireBean()` 用于对现有的Bean实例进行自动装配将依赖注入到Bean中。
- `autowire()` 是在创建Bean实例时使用指定的自动装配模式用于生成新的Bean实例。
3. **autowireBeanProperties() 和 applyBeanPropertyValues()**
- `autowireBeanProperties()` 主要用于对Bean实例的属性进行自动装配。
- `applyBeanPropertyValues()` 则是将属性值应用到Bean实例包括在XML或注解中配置的属性值。
4. **initializeBean()、applyBeanPostProcessorsBeforeInitialization() 和 applyBeanPostProcessorsAfterInitialization()**
- `initializeBean()` 是Bean生命周期中的最后一步包括初始化和应用BeanPostProcessors等。
- `applyBeanPostProcessorsBeforeInitialization()` 用于在初始化之前应用BeanPostProcessors。
- `applyBeanPostProcessorsAfterInitialization()` 用于在初始化之后应用BeanPostProcessors。
5. **destroyBean()**
- `destroyBean()` 用于销毁给定的Bean实例释放资源等。通常在容器关闭时调用。
6. **resolveNamedBean() 和 resolveBeanByName()**
- `resolveNamedBean()` 主要用于解析指定名称的Bean并返回Bean实例。
- `resolveBeanByName()` 则是解析指定名称的Bean定义而不是直接返回Bean实例。
7. **resolveDependency()**
- `resolveDependency()` 主要用于解析Bean之间的依赖关系特别是在自动装配时。在`AbstractAutowireCapableBeanFactory`的`doResolveDependency()`方法中调用。

View File

@ -46,17 +46,11 @@ public class AutowireCapableBeanFactoryDemo {
// autowireBeanProperties(beanFactory);
// 将属性值应用到给定的Bean实例
applyBeanPropertyValues(beanFactory);
// applyBeanPropertyValues(beanFactory);
// 初始化给定的Bean实例
// initializeBean(beanFactory);
// 在初始化之前应用 Bean 后处理器
// applyBeanPostProcessorsBeforeInitialization(beanFactory);
// 初始化后应用 Bean 后处理器
// applyBeanPostProcessorsAfterInitialization(beanFactory);
// 销毁给定的Bean实例
// destroyBean(beanFactory);
@ -121,29 +115,12 @@ public class AutowireCapableBeanFactoryDemo {
System.out.println("调用initializeBean前,MyService = " + myService);
}
private static void applyBeanPostProcessorsBeforeInitialization(AutowireCapableBeanFactory beanFactory) {
MyService myService = new MyService();
System.out.println("调用applyBeanPostProcessorsBeforeInitialization前,MyService = " + myService);
beanFactory.applyBeanPostProcessorsBeforeInitialization(myService, "myService");
System.out.println("调用applyBeanPostProcessorsBeforeInitialization后,MyService = " + myService);
}
private static void applyBeanPostProcessorsAfterInitialization(AutowireCapableBeanFactory beanFactory) {
MyService myService = new MyService();
System.out.println("调用applyBeanPostProcessorsAfterInitialization前,MyService = " + myService);
beanFactory.applyBeanPostProcessorsAfterInitialization(myService, "myService");
System.out.println("调用applyBeanPostProcessorsAfterInitialization后,MyService = " + myService);
}
private static void destroyBean(AutowireCapableBeanFactory beanFactory) {
beanFactory.destroyBean(new MyService());
}
private static void resolveDependency(AutowireCapableBeanFactory beanFactory) {
try {
// 配置一个MyRepository用于被依赖对象注入使用
((DefaultListableBeanFactory) beanFactory).registerSingleton("myRepository", new MyRepository());
DependencyDescriptor dependencyDescriptor = new DependencyDescriptor(MyService.class.getDeclaredField("myRepository"), false);
Object resolveDependency = beanFactory.resolveDependency(dependencyDescriptor, "myRepository");
System.out.println("resolveDependency = " + resolveDependency);