Spring 6.2.2 @scope(“prototype“)原理

Spring @Prototype 原理?

前置准备

  1. 创建一个MyService类
java 复制代码
@Scope("prototype")
@Service("myService")
public class MyService {
    public String getMessage() {
        return "Hello, World!";
    }
}
  1. 创建一个main类,用于debug。

prototype 如何生效?

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

java 复制代码
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

相关推荐
二月夜11 小时前
剖析Java正则表达式回溯问题
java·正则表达式
xuhaoyu_cpp_java12 小时前
项目学习(三)分页查询
java·经验分享·笔记·学习
程序员二叉12 小时前
【Java】集合面试全套精讲|HashMap/ArrayList高频考点完整版
java·面试·哈希算法
cfm_291412 小时前
JVM GC垃圾回收初步了解
java·开发语言·jvm
心之伊始12 小时前
LangChain4j RAG 实战:Java 后端如何把本地文档接入 Embedding 检索链路
java·架构·源码分析·csdn
许彰午13 小时前
17_synchronized关键字深度解析
java·开发语言
Xzh042314 小时前
AI Agent 学习路线(Java 后端方向)
java·人工智能·学习
艾利克斯冰15 小时前
Java 设计模式-行为型模式(更新中)
java·开发语言·设计模式
倒霉蛋小马15 小时前
Java新特性:record关键字
java·开发语言
折哥的程序人生 · 物流技术专研16 小时前
《Java 100 天进阶之路》第95篇:消息队列基础(RocketMQ/Kafka)(2026版)
java·面试·kafka·rocketmq·java-rocketmq·求职招聘