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

相关推荐
青木川崎1 天前
linux面试题
java·linux·运维
浮游本尊1 天前
Java学习第28天 - 大规模系统设计与性能优化
java
上下翻飞的屁1 天前
jdbcTemplate执行sql后数据库字段没有更新问题解决
java·数据库·sql
爱宇阳1 天前
Java Spring Boot 项目 Docker 容器化部署教程
java·spring boot·docker
Luo_xguan1 天前
一、Netty-高并发IO底层原理(5种主要的IO模型)
java·服务器·netty·nio
ACGkaka_1 天前
SpringBoot 实战(四十)集成 Statemachine
java·spring boot·后端
开开心心就好1 天前
电脑音质提升:杜比全景声安装详细教程
java·开发语言·前端·数据库·电脑·ruby·1024程序员节
yoi啃码磕了牙1 天前
Unity—Localization 多语言
java·数据库·mysql
跟着珅聪学java1 天前
在Java中判断Word文档中是否包含表格并读取表格内容,可以使用Apache POI库教程
java·开发语言·word