Spring 源码解读:实现单例与原型的Bean作用域

2024-08-30 07:20

本文主要是介绍Spring 源码解读:实现单例与原型的Bean作用域,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

引言

在Spring框架中,Bean的作用域(Scope)定义了Bean的生命周期和访问范围。Spring提供了多种作用域,包括常用的单例(Singleton)和原型(Prototype)。了解并正确使用这些作用域对于管理应用的资源和性能至关重要。本篇文章将通过手动实现单例和原型作用域的Bean管理机制,并对比Spring中的@Scope注解,帮助你理解不同Bean作用域的使用场景和实现细节。

Bean作用域的基本概念

在Spring中,Bean的作用域决定了容器如何创建和管理Bean实例。不同的作用域适用于不同的使用场景:

常见的Bean作用域

  1. 单例(Singleton)

    • 默认作用域。
    • Spring容器在整个生命周期内仅创建一个Bean实例,并在需要时返回相同的实例。
    • 适用于无状态的服务类或数据访问对象。
  2. 原型(Prototype)

    • 每次请求都会创建一个新的Bean实例。
    • 适用于有状态的对象或需要频繁创建的对象。

手动实现单例与原型作用域的Bean管理

为了实现单例和原型作用域的Bean管理机制,我们需要:

  1. 定义一个BeanFactory接口,提供获取Bean实例的基本方法。
  2. 实现一个支持单例作用域的Bean工厂。
  3. 实现一个支持原型作用域的Bean工厂。
  4. 实现一个通用的Bean工厂,根据Bean的配置决定使用哪种作用域。

定义BeanFactory接口

BeanFactory接口提供了获取Bean实例的基本方法。

/*** BeanFactory接口,定义了获取Bean实例的基本方法*/
public interface BeanFactory {/*** 获取Bean实例* @param name Bean的名称* @return Bean实例*/Object getBean(String name);
}

实现单例作用域的Bean工厂

SingletonBeanFactory类实现了BeanFactory接口,负责管理单例作用域的Bean。

import java.util.HashMap;
import java.util.Map;/*** 单例作用域的Bean工厂*/
public class SingletonBeanFactory implements BeanFactory {private Map<String, Object> singletonBeans = new HashMap<>();/*** 获取单例Bean实例* @param name Bean的名称* @return 单例Bean实例*/@Overridepublic Object getBean(String name) {return singletonBeans.get(name);}/*** 注册单例Bean* @param name Bean的名称* @param bean Bean实例*/public void registerSingleton(String name, Object bean) {singletonBeans.put(name, bean);}
}

实现原型作用域的Bean工厂

PrototypeBeanFactory类同样实现了BeanFactory接口,但每次调用getBean方法时都会创建一个新的Bean实例。

import java.util.function.Supplier;/*** 原型作用域的Bean工厂*/
public class PrototypeBeanFactory implements BeanFactory {private Map<String, Supplier<Object>> beanSuppliers = new HashMap<>();/*** 获取原型Bean实例* @param name Bean的名称* @return 新的Bean实例*/@Overridepublic Object getBean(String name) {Supplier<Object> supplier = beanSuppliers.get(name);if (supplier != null) {return supplier.get();}return null;}/*** 注册原型Bean的创建方法* @param name Bean的名称* @param supplier 创建Bean实例的方法*/public void registerPrototype(String name, Supplier<Object> supplier) {beanSuppliers.put(name, supplier);}
}

实现通用的Bean工厂

GenericBeanFactory类根据配置决定使用哪种作用域,并提供通用的Bean管理机制。

import java.util.HashMap;
import java.util.Map;/*** 通用的Bean工厂,支持单例和原型作用域*/
public class GenericBeanFactory implements BeanFactory {private SingletonBeanFactory singletonBeanFactory = new SingletonBeanFactory();private PrototypeBeanFactory prototypeBeanFactory = new PrototypeBeanFactory();private Map<String, String> beanScopes = new HashMap<>();/*** 获取Bean实例,根据Bean的作用域决定返回单例还是新的实例* @param name Bean的名称* @return Bean实例*/@Overridepublic Object getBean(String name) {String scope = beanScopes.get(name);if ("singleton".equals(scope)) {return singletonBeanFactory.getBean(name);} else if ("prototype".equals(scope)) {return prototypeBeanFactory.getBean(name);}return null;}/*** 注册单例Bean* @param name Bean的名称* @param bean Bean实例*/public void registerSingleton(String name, Object bean) {singletonBeanFactory.registerSingleton(name, bean);beanScopes.put(name, "singleton");}/*** 注册原型Bean的创建方法* @param name Bean的名称* @param supplier 创建Bean实例的方法*/public void registerPrototype(String name, Supplier<Object> supplier) {prototypeBeanFactory.registerPrototype(name, supplier);beanScopes.put(name, "prototype");}
}

创建测试类

我们通过一个简单的测试类来验证单例和原型作用域的管理机制。

public class AppConfig {public static void main(String[] args) {GenericBeanFactory beanFactory = new GenericBeanFactory();// 注册单例BeanbeanFactory.registerSingleton("singletonBean", new SingletonService());// 注册原型BeanbeanFactory.registerPrototype("prototypeBean", PrototypeService::new);// 获取单例BeanSingletonService singletonBean1 = (SingletonService) beanFactory.getBean("singletonBean");SingletonService singletonBean2 = (SingletonService) beanFactory.getBean("singletonBean");System.out.println("Singleton Beans are same: " + (singletonBean1 == singletonBean2));// 获取原型BeanPrototypeService prototypeBean1 = (PrototypeService) beanFactory.getBean("prototypeBean");PrototypeService prototypeBean2 = (PrototypeService) beanFactory.getBean("prototypeBean");System.out.println("Prototype Beans are same: " + (prototypeBean1 == prototypeBean2));}
}class SingletonService {// 单例服务的示例类
}class PrototypeService {// 原型服务的示例类
}

测试结果

  • 输出 Singleton Beans are same: true 表明单例Bean每次获取的都是相同的实例。
  • 输出 Prototype Beans are same: false 表明原型Bean每次获取的都是新的实例。

类图和流程图

为了更好地理解整个流程,我们提供了类图和流程图。

类图
BeanFactory
+Object getBean(String name)
SingletonBeanFactory
+Object getBean(String name)
+void registerSingleton(String name, Object bean)
PrototypeBeanFactory
+Object getBean(String name)
+void registerPrototype(String name, Supplier<Object> supplier)
GenericBeanFactory
+Object getBean(String name)
+void registerSingleton(String name, Object bean)
+void registerPrototype(String name, Supplier<Object> supplier)

解释

  • BeanFactory是一个通用接口,定义了获取Bean实例的方法。
  • SingletonBeanFactory实现了单例作用域的Bean管理。
  • PrototypeBeanFactory实现了原型作用域的Bean管理。
  • GenericBeanFactory通过组合模式支持多种作用域的Bean管理。
流程图
单例
原型
GenericBeanFactory
根据Bean名称查找作用域
作用域是单例还是原型?
从SingletonBeanFactory获取Bean
从PrototypeBeanFactory获取Bean
返回单例Bean实例
创建并返回新的Bean实例

解释

  • 流程图展示了GenericBeanFactory如何根据Bean的作用域从不同的工厂获取Bean实例的过程。

Spring中的@Scope注解

@Scope注解的基本实现

在Spring中,@Scope注解用于指定Bean的作用域。@Scope可以与@Component@Bean一起使用,指定Bean是单例还是原型。

@Component
@Scope("prototype")
public class MyPrototypeBean {//这个Bean将会在每次注入时创建新的实例
}@Component
@Scope("singleton")
public class MySingletonBean {// 这个Bean将会在容器中创建一次,并在每次注入时返回相同的实例
}

@Scope注解的底层实现

Spring通过ScopedProxyFactoryBean类和ProxyMode属性来实现不同作用域的Bean管理。它支持包括单例、原型、请求作用域、会话作用域等多种作用域。

public class ScopedProxyFactoryBean extends ProxyFactoryBean {private BeanFactory beanFactory;public ScopedProxyFactoryBean(BeanFactory beanFactory) {this.beanFactory = beanFactory;}@Overridepublic Object getObject() throws BeansException {return createScopedProxy();}protected Object createScopedProxy() {// 创建适合指定作用域的代理对象}
}

详细解读

  • ScopedProxyFactoryBean类是Spring中用于管理Bean作用域的关键类,通过它可以根据作用域生成合适的代理对象。
  • createScopedProxy方法中,Spring根据Bean的作用域选择使用JDK动态代理或CGLIB生成代理对象。

总结

通过实现单例和原型作用域的Bean管理机制,并深入解读Spring中的@Scope注解的基本实现,你应该对Bean作用域的概念和使用场景有了更深入的理解。不同的Bean作用域在实际项目中的选择和应用,直接影响应用的性能和资源管理,希望这些内容能帮助你更好地掌握Spring框架的相关知识。


互动与思考

在实际项目中,你更倾向于使用单例还是原型作用域?你认为在哪些场景下应该使用原型作用域?欢迎在评论区分享你的看法和经验!


如果你觉得这篇文章对你有帮助,请别忘了:

  • 点赞
  • 收藏 📁
  • 关注 👀

让我们一起深入学习Spring框架,成为更优秀的开发者!


这篇关于Spring 源码解读:实现单例与原型的Bean作用域的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1120158

相关文章

SpringBoot中六种批量更新Mysql的方式效率对比分析

《SpringBoot中六种批量更新Mysql的方式效率对比分析》文章比较了MySQL大数据量批量更新的多种方法,指出REPLACEINTO和ONDUPLICATEKEY效率最高但存在数据风险,MyB... 目录效率比较测试结构数据库初始化测试数据批量修改方案第一种 for第二种 case when第三种

python生成随机唯一id的几种实现方法

《python生成随机唯一id的几种实现方法》在Python中生成随机唯一ID有多种方法,根据不同的需求场景可以选择最适合的方案,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习... 目录方法 1:使用 UUID 模块(推荐)方法 2:使用 Secrets 模块(安全敏感场景)方法

Java docx4j高效处理Word文档的实战指南

《Javadocx4j高效处理Word文档的实战指南》对于需要在Java应用程序中生成、修改或处理Word文档的开发者来说,docx4j是一个强大而专业的选择,下面我们就来看看docx4j的具体使用... 目录引言一、环境准备与基础配置1.1 Maven依赖配置1.2 初始化测试类二、增强版文档操作示例2.

一文详解如何使用Java获取PDF页面信息

《一文详解如何使用Java获取PDF页面信息》了解PDF页面属性是我们在处理文档、内容提取、打印设置或页面重组等任务时不可或缺的一环,下面我们就来看看如何使用Java语言获取这些信息吧... 目录引言一、安装和引入PDF处理库引入依赖二、获取 PDF 页数三、获取页面尺寸(宽高)四、获取页面旋转角度五、判断

Spring Boot中的路径变量示例详解

《SpringBoot中的路径变量示例详解》SpringBoot中PathVariable通过@PathVariable注解实现URL参数与方法参数绑定,支持多参数接收、类型转换、可选参数、默认值及... 目录一. 基本用法与参数映射1.路径定义2.参数绑定&nhttp://www.chinasem.cnbs

JAVA中安装多个JDK的方法

《JAVA中安装多个JDK的方法》文章介绍了在Windows系统上安装多个JDK版本的方法,包括下载、安装路径修改、环境变量配置(JAVA_HOME和Path),并说明如何通过调整JAVA_HOME在... 首先去oracle官网下载好两个版本不同的jdk(需要登录Oracle账号,没有可以免费注册)下载完

Spring StateMachine实现状态机使用示例详解

《SpringStateMachine实现状态机使用示例详解》本文介绍SpringStateMachine实现状态机的步骤,包括依赖导入、枚举定义、状态转移规则配置、上下文管理及服务调用示例,重点解... 目录什么是状态机使用示例什么是状态机状态机是计算机科学中的​​核心建模工具​​,用于描述对象在其生命

Spring Boot 结合 WxJava 实现文章上传微信公众号草稿箱与群发

《SpringBoot结合WxJava实现文章上传微信公众号草稿箱与群发》本文将详细介绍如何使用SpringBoot框架结合WxJava开发工具包,实现文章上传到微信公众号草稿箱以及群发功能,... 目录一、项目环境准备1.1 开发环境1.2 微信公众号准备二、Spring Boot 项目搭建2.1 创建

Java中Integer128陷阱

《Java中Integer128陷阱》本文主要介绍了Java中Integer与int的区别及装箱拆箱机制,重点指出-128至127范围内的Integer值会复用缓存对象,导致==比较结果为true,下... 目录一、Integer和int的联系1.1 Integer和int的区别1.2 Integer和in

SpringSecurity整合redission序列化问题小结(最新整理)

《SpringSecurity整合redission序列化问题小结(最新整理)》文章详解SpringSecurity整合Redisson时的序列化问题,指出需排除官方Jackson依赖,通过自定义反序... 目录1. 前言2. Redission配置2.1 RedissonProperties2.2 Red