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

相关推荐
找不到、了31 分钟前
分布式理论:CAP、Base理论
java·分布式
天天摸鱼的java工程师34 分钟前
2025已过半,Java就业大环境究竟咋样了?
java·后端
人生在勤,不索何获-白大侠38 分钟前
day16——Java集合进阶(Collection、List、Set)
java·开发语言
Zedthm44 分钟前
LeetCode1004. 最大连续1的个数 III
java·算法·leetcode
艺杯羹1 小时前
MyBatis之核心对象与工作流程及SqlSession操作
java·mybatis
神的孩子都在歌唱1 小时前
3423. 循环数组中相邻元素的最大差值 — day97
java·数据结构·算法
喜欢吃豆2 小时前
深入企业内部的MCP知识(三):FastMCP工具转换(Tool Transformation)全解析:从适配到增强的工具进化指南
java·前端·人工智能·大模型·github·mcp
用户1551733938832 小时前
前后端处理 `multipart/form-data` 混合参数(实体对象+文件)方案
java
东阳马生架构2 小时前
订单初版—3.支付和履约链路中的技术问题说明文档
java
留不住丨晚霞2 小时前
说说SpringBoot常用的注解?
java·开发语言