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

相关推荐
Orange30151116 分钟前
ES6~ES11新特性全解析
java·前端·javascript·es6
程序员林北北1 小时前
【Golang学习之旅】gRPC 与 REST API 的对比及应用
java·开发语言·后端·学习·云原生·golang
一川晚照人闲立2 小时前
JEECGBOOT前端VUE3版本浏览器兼容支持chrome>=76版本方法
java·前端·vue.js·chrome·anti-design-vue·jeecgboot·jeecg
0wioiw02 小时前
Python基础(SQLAlchemy)
java·开发语言·数据库
Luo_LA2 小时前
【Java 面试 八股文】Redis篇
java·redis·面试
ChinaRainbowSea2 小时前
十四. Redis 新功能
java·数据库·redis·缓存·bootstrap
小胖子——鑫3 小时前
对“云原生”的初印象
java·开发语言·云原生
归宿乐瑶3 小时前
六.logback记录日志文件并按大小日期分割文件
java·spring boot·logback
朝屯暮蒙vi3 小时前
(五)Spring Boot学习——spring security +jwt使用(前后端分离模式)
spring boot·学习·spring·spring security
码蜂窝编程官方3 小时前
【含开题报告+文档+PPT+源码】基于SpringBoot+Vue旅游管理网站
java·vue.js·spring boot·旅游