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

相关推荐
Dorcas_FE20 分钟前
axios请求缓存与重复拦截:“相同请求未完成时,不发起新请求”
前端·spring·缓存
小薛博客42 分钟前
22、Jenkins容器化部署Java应用
java·运维·jenkins
西贝爱学习1 小时前
如何在 IntelliJ IDEA 中进行全局替换某个字段(或文本)
java·ide·intellij-idea
南部余额1 小时前
Spring 基于注解的自动化事务
java·spring·自动化
alf_cee1 小时前
通过Idea 阿里插件快速部署java jar包
java·ide·intellij-idea
坚持每天敲代码1 小时前
【教程】IDEA中导入springboot-maven工程
java·maven·intellij-idea
CodeCraft Studio1 小时前
国产化PDF处理控件Spire.PDF教程:如何在 Java 中通过模板生成 PDF
java·python·pdf·spire.pdf·java创建pdf·从html创建pdf
阿方.9182 小时前
《数据结构全解析:栈(数组实现)》
java·开发语言·数据结构
YC运维2 小时前
Ansible题目全解析与答案
java·算法·ansible
程序员清风2 小时前
贝壳一面:年轻代回收频率太高,如何定位?
java·后端·面试