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

相关推荐
冬天vs不冷4 分钟前
Java基础(九):Object核心类深度剖析
java·开发语言·python
悟空聊架构24 分钟前
我的网站被攻击了,被干掉了 120G 流量,还在持续攻击中...
java·前端·架构
Dajiaonew1 小时前
Spring AI RAG 检索增强 应用
java·人工智能·spring·ai·langchain
IT古董4 小时前
第四章:大模型(LLM)】06.langchain原理-(3)LangChain Prompt 用法
java·人工智能·python
轻抚酸~7 小时前
小迪23年-32~40——java简单回顾
java·web安全
Sirius Wu9 小时前
Maven环境如何正确配置
java·maven
健康平安的活着10 小时前
java之 junit4单元测试Mockito的使用
java·开发语言·单元测试
Java小白程序员11 小时前
Spring Framework :IoC 容器的原理与实践
java·后端·spring
xuTao66711 小时前
Easy Rules 规则引擎详解
java·easy rules
m0_4805026412 小时前
Rust 入门 KV存储HashMap (十七)
java·开发语言·rust