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

相关推荐
SunnyDays10112 分钟前
Java实战指南:如何高效将PDF转换为高质量TIFF图片
java·pdf转tiff
Seven975 分钟前
【从0到1构建一个ClaudeAgent】规划与协调-TodoWrite
java
Yeh2020587 分钟前
maven
java·maven
色空大师7 分钟前
【java打包方式详解】
java·开发语言·部署·打包·启动脚本·jar包分离
人道领域8 分钟前
2026年Java后端热点全景解析:从LTS革新到云原生跃迁
java·开发语言
鱼鳞_10 分钟前
Java学习笔记_Day26(不可变集合)
java·笔记·学习
zhaoyufei13312 分钟前
RK3566 EDP屏幕背光闪修改pwm
android·java
清心歌21 分钟前
HashMap实现原理及扩容机制
java
一只大袋鼠21 分钟前
数据库连接池从入门到精通(下):Druid 连接池使用与工具类封装
java·数据库·连接池
禹中一只鱼24 分钟前
【IDEA 出现 `IDE error occurred`】
java·ide·spring boot·intellij-idea