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

相关推荐
海盗123416 小时前
C#中PDF操作-QuestPDF页面设置与布局
java·pdf·c#
day day day ...17 小时前
MyBatis / MyBatis-Plus 动态 SQL 中 OGNL 表达式的常见陷阱与源码分析
java·开发语言·mybatis
Kiling_070417 小时前
Java IO流:字节流实战与性能优化
java·开发语言·php
January120717 小时前
IDEA 快捷键
java·ide·intellij-idea
周杰伦fans17 小时前
C# 异常继承深度解析:从设计原则到 sealed 关键字的奥秘
java·jvm·c#
搬石头的马农17 小时前
从零配置Claude自动修Bug:6步打造全自动开发流程
java·人工智能·python·bug·ai编程
小马爱打代码17 小时前
Redis Key 过期后会立刻删除吗?过期删除与内存淘汰策略详解
java·redis·缓存
鱼鳞_17 小时前
苍穹外卖-Day10(Spring task)
java·后端·spring
雨落在了我的手上17 小时前
初始java(十七):常⽤⼯具类介绍
java·开发语言
凤凰院凶涛QAQ18 小时前
《Java版数据结构 & 集合类剖析》集合框架的封装设计与顺序表:“从 Iterable 到 ArrayList:集合框架的‘职业树“
java·开发语言·数据结构