揭密springboot自动装配(5)--ioc及@Autowired注解

2024-06-04 19:18

本文主要是介绍揭密springboot自动装配(5)--ioc及@Autowired注解,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

@Autowired 注解的bean什么时候实例化给它?


我们直接从AbstractAutowireCapableBeanFactory.doCreateBean开始,这个方法从上一章内容可得知是创建实例化对象然后放入三级缓存的singletonFactories里面,我们接着这个方法继续深究

protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)throws BeanCreationException {// Instantiate the bean.BeanWrapper instanceWrapper = null;if (mbd.isSingleton()) {instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);}if (instanceWrapper == null) {instanceWrapper = createBeanInstance(beanName, mbd, args);}final Object bean = instanceWrapper.getWrappedInstance();Class<?> beanType = instanceWrapper.getWrappedClass();if (beanType != NullBean.class) {mbd.resolvedTargetType = beanType;}// Allow post-processors to modify the merged bean definition.synchronized (mbd.postProcessingLock) {if (!mbd.postProcessed) {try {applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);}catch (Throwable ex) {throw new BeanCreationException(mbd.getResourceDescription(), beanName,"Post-processing of merged bean definition failed", ex);}mbd.postProcessed = true;}}// Eagerly cache singletons to be able to resolve circular references// even when triggered by lifecycle interfaces like BeanFactoryAware.boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&isSingletonCurrentlyInCreation(beanName));if (earlySingletonExposure) {if (logger.isTraceEnabled()) {logger.trace("Eagerly caching bean '" + beanName +"' to allow for resolving potential circular references");}addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));}// Initialize the bean instance.Object exposedObject = bean;try {populateBean(beanName, mbd, instanceWrapper);exposedObject = initializeBean(beanName, exposedObject, mbd);}catch (Throwable ex) {if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {throw (BeanCreationException) ex;}else {throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);}}if (earlySingletonExposure) {Object earlySingletonReference = getSingleton(beanName, false);if (earlySingletonReference != null) {if (exposedObject == bean) {exposedObject = earlySingletonReference;}else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {String[] dependentBeans = getDependentBeans(beanName);Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);for (String dependentBean : dependentBeans) {if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {actualDependentBeans.add(dependentBean);}}if (!actualDependentBeans.isEmpty()) {throw new BeanCurrentlyInCreationException(beanName,"Bean with name '" + beanName + "' has been injected into other beans [" +StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +"] in its raw version as part of a circular reference, but has eventually been " +"wrapped. This means that said other beans do not use the final version of the " +"bean. This is often the result of over-eager type matching - consider using " +"'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");}}}}// Register bean as disposable.try {registerDisposableBeanIfNecessary(beanName, bean, mbd);}catch (BeanDefinitionValidationException ex) {throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);}return exposedObject;}

这里可以看到bean实例化之后放入三级缓存接着就会进入populateBean方法进行判断该实例化对象是否有@Autowired注解,有的话会进行@Autowired的对应的bean的获取或创建,废话不多说,直接看代码:下面populateBean部分关键代码

AbstractAutowireCapableBeanFactory.populateBean方法我们看如图,遍历所有beanPostProcessors

这里的beanPostProcessors是在AbstractApplicationContext.refresh方法里registerBeanPostProcessors(beanFactory);放进去的,里面有对应的AutowiredAnnotationBeanPostProcessor,这个就是专门处理@Autowired注解的

接着调用PropertyValues pvsToUse = (AutowiredAnnotationBeanPostProcessor)ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);

这个方法里面可看到findAutowiringMetadata进行查询所有注解信息,可以看到拿到了usera这个属性

private com.example.demo.service.UserA com.example.demo.service.UserB.usera

我们进入AutowiredAnnotationBeanPostProcessor.findAutowiringMetadata

接着AutowiredAnnotationBeanPostProcessor.buildAutowiringMetadata

AutowiredAnnotationBeanPostProcessor.findAutowiredAnnotation

this.autowiredAnnotationTypes这里面放的就是在AbstractApplicationContext.refresh方法里registerBeanPostProcessors(beanFactory)构造AutowiredAnnotationBeanPostProcessor时放入的@Autowired

返回这里:

然后调用metadata.inject(bean, beanName, pvs)进行对应属性usera初始化,继续往里走

AutowiredAnnotationBeanPostProcessor.inject()

DefaultListableBeanFactory.resolveDependency()

DefaultListableBeanFactory.doResolveDependency(),该方法里面继续调用DependencyDescriptor.resolveCandidate

DependencyDescriptor.resolveCandidate到这个方法里面就会发现一个熟悉的东西AbstractBeanFactory.getBean(beanName)

这不就是上章提到的获取bean嘛

调用这里将会进行对象获取如果获取不到就接着userA实例化,这就是一个递归

顺带提一下上节提到的三级缓存解决依赖注解的问题,从这里我们就可以看到,bean实例化时候将进入三级缓存,然后接着一系列操作看实例化的bean是否里面有@Autowired这样的注解,有的话接着对应属性的bean实例化,没有的话就将三级缓存的bean 放入一级缓存中

我们创建往userA之后接着回到AutowiredAnnotationBeanPostProcessor.inject()方法,最后将创建好的bean放入对应field里面完成@Autowired注解的属性的实例化

 

这篇关于揭密springboot自动装配(5)--ioc及@Autowired注解的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1030888

相关文章

分布式锁在Spring Boot应用中的实现过程

《分布式锁在SpringBoot应用中的实现过程》文章介绍在SpringBoot中通过自定义Lock注解、LockAspect切面和RedisLockUtils工具类实现分布式锁,确保多实例并发操作... 目录Lock注解LockASPect切面RedisLockUtils工具类总结在现代微服务架构中,分布

Java使用Thumbnailator库实现图片处理与压缩功能

《Java使用Thumbnailator库实现图片处理与压缩功能》Thumbnailator是高性能Java图像处理库,支持缩放、旋转、水印添加、裁剪及格式转换,提供易用API和性能优化,适合Web应... 目录1. 图片处理库Thumbnailator介绍2. 基本和指定大小图片缩放功能2.1 图片缩放的

Spring Boot集成/输出/日志级别控制/持久化开发实践

《SpringBoot集成/输出/日志级别控制/持久化开发实践》SpringBoot默认集成Logback,支持灵活日志级别配置(INFO/DEBUG等),输出包含时间戳、级别、类名等信息,并可通过... 目录一、日志概述1.1、Spring Boot日志简介1.2、日志框架与默认配置1.3、日志的核心作用

Python使用Tenacity一行代码实现自动重试详解

《Python使用Tenacity一行代码实现自动重试详解》tenacity是一个专为Python设计的通用重试库,它的核心理念就是用简单、清晰的方式,为任何可能失败的操作添加重试能力,下面我们就来看... 目录一切始于一个简单的 API 调用Tenacity 入门:一行代码实现优雅重试精细控制:让重试按我

破茧 JDBC:MyBatis 在 Spring Boot 中的轻量实践指南

《破茧JDBC:MyBatis在SpringBoot中的轻量实践指南》MyBatis是持久层框架,简化JDBC开发,通过接口+XML/注解实现数据访问,动态代理生成实现类,支持增删改查及参数... 目录一、什么是 MyBATis二、 MyBatis 入门2.1、创建项目2.2、配置数据库连接字符串2.3、入

Springboot项目启动失败提示找不到dao类的解决

《Springboot项目启动失败提示找不到dao类的解决》SpringBoot启动失败,因ProductServiceImpl未正确注入ProductDao,原因:Dao未注册为Bean,解决:在启... 目录错误描述原因解决方法总结***************************APPLICA编

深度解析Spring Security 中的 SecurityFilterChain核心功能

《深度解析SpringSecurity中的SecurityFilterChain核心功能》SecurityFilterChain通过组件化配置、类型安全路径匹配、多链协同三大特性,重构了Spri... 目录Spring Security 中的SecurityFilterChain深度解析一、Security

SpringBoot多环境配置数据读取方式

《SpringBoot多环境配置数据读取方式》SpringBoot通过环境隔离机制,支持properties/yaml/yml多格式配置,结合@Value、Environment和@Configura... 目录一、多环境配置的核心思路二、3种配置文件格式详解2.1 properties格式(传统格式)1.

Apache Ignite 与 Spring Boot 集成详细指南

《ApacheIgnite与SpringBoot集成详细指南》ApacheIgnite官方指南详解如何通过SpringBootStarter扩展实现自动配置,支持厚/轻客户端模式,简化Ign... 目录 一、背景:为什么需要这个集成? 二、两种集成方式(对应两种客户端模型) 三、方式一:自动配置 Thick

SQL Server跟踪自动统计信息更新实战指南

《SQLServer跟踪自动统计信息更新实战指南》本文详解SQLServer自动统计信息更新的跟踪方法,推荐使用扩展事件实时捕获更新操作及详细信息,同时结合系统视图快速检查统计信息状态,重点强调修... 目录SQL Server 如何跟踪自动统计信息更新:深入解析与实战指南 核心跟踪方法1️⃣ 利用系统目录