当前位置: 首页 > article >正文

Spring 6.2.2 @scope(“prototype“)原理

Spring @Prototype 原理?

前置准备

  1. 创建一个MyService类
@Scope("prototype")
@Service("myService")
public class MyService {
    public String getMessage() {
        return "Hello, World!";
    }
}
  1. 创建一个main类,用于debug。
    在这里插入图片描述

prototype 如何生效?

context.getBean();方法中,有一个核心方法doGetBean()

protected <T> T doGetBean(
			String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly)
			throws BeansException {
			......省略
			try {
				// Create bean instance.
				if (mbd.isSingleton()) {
					sharedInstance = getSingleton(beanName, () -> {
						try {
							return createBean(beanName, mbd, args);
						}
						catch (BeansException ex) {
							// Explicitly remove instance from singleton cache: It might have been put there
							// eagerly by the creation process, to allow for circular reference resolution.
							// Also remove any beans that received a temporary reference to the bean.
							destroySingleton(beanName);
							throw ex;
						}
					});
					beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
				}

				else if (mbd.isPrototype()) {
					// It's a prototype -> create a new instance.
					Object prototypeInstance = null;
					try {
						beforePrototypeCreation(beanName);
						prototypeInstance = createBean(beanName, mbd, args);
					}
					finally {
						afterPrototypeCreation(beanName);
					}
					beanInstance = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
				}

				....省略

		return adaptBeanInstance(name, beanInstance, requiredType);
	}

存在一个判断:else if (mbd.isPrototype())bean definitionscopeprototype的时候调用createBean()将创建一个新的bean


http://www.kler.cn/a/538153.html

相关文章:

  • http常用状态码
  • Windows下AMD显卡在本地运行大语言模型(deepseek-r1)
  • 【C++篇】 异常处理
  • 练习题(2025.2.9)
  • 物联网软件开发与应用方向应该怎样学习,学习哪些内容,就业方向是怎样?(文末领取整套学习视频,课件)物联网硬件开发与嵌入式系统
  • 基于机器学习的DDoS检测系统实战
  • [渗透测试]热门搜索引擎推荐— — fofa篇
  • 【生成模型之十四】Visual Autoregressive Modeling
  • 13.3 使用 Chat Prompt Template 设计专业翻译提示模板
  • 4.3 线性回归的改进-岭回归/4.4分类算法-逻辑回归与二分类/ 4.5 模型保存和加载
  • OC-Block
  • 全志A133 android10 thermal温控策略配置调试
  • ML.NET库学习003:基于时间序列的共享单车需求预测项目解析
  • 即时通讯开源项目OpenIM配置离线推送全攻略
  • 练习题 - Django 4.x Session 会话使用示例和配置方法
  • 数据结构:算法复杂度
  • python - 封装moondream(备份)
  • html css网页制作成品——HTML+CSS茶百道的茶网页设计(6页)附源码
  • 数据结构--八大排序算法
  • C06S02-Docker网络和资源限制
  • 3D gpr仿真
  • 使用 SDKMAN! 在 Mac(包括 ARM 架构的 M1/M2 芯片)上安装 Java 8
  • 深度解析DeepSeek模型系列:从轻量级到超大规模(附DeepSeek硬件配置清单)
  • 【C++语法】【STL】“for ( auto c : str )”类型的循环
  • FreeRtos实时系统: 九.FreeRTOS的时间管理
  • 【学Rust写CAD】5 三维转换矩阵解析及应用示例