爆款云主机2核4G限时秒杀,88元/年起!
查看详情

活动

天翼云最新优惠活动,涵盖免费试用,产品折扣等,助您降本增效!
热门活动
  • 618智算钜惠季 爆款云主机2核4G限时秒杀,88元/年起!
  • 免费体验DeepSeek,上天翼云息壤 NEW 新老用户均可免费体验2500万Tokens,限时两周
  • 云上钜惠 HOT 爆款云主机全场特惠,更有万元锦鲤券等你来领!
  • 算力套餐 HOT 让算力触手可及
  • 天翼云脑AOne NEW 连接、保护、办公,All-in-One!
  • 中小企业应用上云专场 产品组合下单即享折上9折起,助力企业快速上云
  • 息壤高校钜惠活动 NEW 天翼云息壤杯高校AI大赛,数款产品享受线上订购超值特惠
  • 天翼云电脑专场 HOT 移动办公新选择,爆款4核8G畅享1年3.5折起,快来抢购!
  • 天翼云奖励推广计划 加入成为云推官,推荐新用户注册下单得现金奖励
免费活动
  • 免费试用中心 HOT 多款云产品免费试用,快来开启云上之旅
  • 天翼云用户体验官 NEW 您的洞察,重塑科技边界

智算服务

打造统一的产品能力,实现算网调度、训练推理、技术架构、资源管理一体化智算服务
智算云(DeepSeek专区)
科研助手
  • 算力商城
  • 应用商城
  • 开发机
  • 并行计算
算力互联调度平台
  • 应用市场
  • 算力市场
  • 算力调度推荐
一站式智算服务平台
  • 模型广场
  • 体验中心
  • 服务接入
智算一体机
  • 智算一体机
大模型
  • DeepSeek-R1-昇腾版(671B)
  • DeepSeek-R1-英伟达版(671B)
  • DeepSeek-V3-昇腾版(671B)
  • DeepSeek-R1-Distill-Llama-70B
  • DeepSeek-R1-Distill-Qwen-32B
  • Qwen2-72B-Instruct
  • StableDiffusion-V2.1
  • TeleChat-12B

应用商城

天翼云精选行业优秀合作伙伴及千余款商品,提供一站式云上应用服务
进入甄选商城进入云市场创新解决方案
办公协同
  • WPS云文档
  • 安全邮箱
  • EMM手机管家
  • 智能商业平台
财务管理
  • 工资条
  • 税务风控云
企业应用
  • 翼信息化运维服务
  • 翼视频云归档解决方案
工业能源
  • 智慧工厂_生产流程管理解决方案
  • 智慧工地
建站工具
  • SSL证书
  • 新域名服务
网络工具
  • 翼云加速
灾备迁移
  • 云管家2.0
  • 翼备份
资源管理
  • 全栈混合云敏捷版(软件)
  • 全栈混合云敏捷版(一体机)
行业应用
  • 翼电子教室
  • 翼智慧显示一体化解决方案

合作伙伴

天翼云携手合作伙伴,共创云上生态,合作共赢
天翼云生态合作中心
  • 天翼云生态合作中心
天翼云渠道合作伙伴
  • 天翼云代理渠道合作伙伴
天翼云服务合作伙伴
  • 天翼云集成商交付能力认证
天翼云应用合作伙伴
  • 天翼云云市场合作伙伴
  • 天翼云甄选商城合作伙伴
天翼云技术合作伙伴
  • 天翼云OpenAPI中心
  • 天翼云EasyCoding平台
天翼云培训认证
  • 天翼云学堂
  • 天翼云市场商学院
天翼云合作计划
  • 云汇计划
天翼云东升计划
  • 适配中心
  • 东升计划
  • 适配互认证

开发者

开发者相关功能入口汇聚
技术社区
  • 专栏文章
  • 互动问答
  • 技术视频
资源与工具
  • OpenAPI中心
开放能力
  • EasyCoding敏捷开发平台
培训与认证
  • 天翼云学堂
  • 天翼云认证
魔乐社区
  • 魔乐社区

支持与服务

为您提供全方位支持与服务,全流程技术保障,助您轻松上云,安全无忧
文档与工具
  • 文档中心
  • 新手上云
  • 自助服务
  • OpenAPI中心
定价
  • 价格计算器
  • 定价策略
基础服务
  • 售前咨询
  • 在线支持
  • 在线支持
  • 工单服务
  • 建议与反馈
  • 用户体验官
  • 服务保障
  • 客户公告
  • 会员中心
增值服务
  • 红心服务
  • 首保服务
  • 客户支持计划
  • 专家技术服务
  • 备案管家

了解天翼云

天翼云秉承央企使命,致力于成为数字经济主力军,投身科技强国伟大事业,为用户提供安全、普惠云服务
品牌介绍
  • 关于天翼云
  • 智算云
  • 天翼云4.0
  • 新闻资讯
  • 天翼云APP
基础设施
  • 全球基础设施
  • 信任中心
最佳实践
  • 精选案例
  • 超级探访
  • 云杂志
  • 分析师和白皮书
  • 天翼云·创新直播间
市场活动
  • 2025智能云生态大会
  • 2024智算云生态大会
  • 2023云生态大会
  • 2022云生态大会
  • 天翼云中国行
天翼云
  • 活动
  • 智算服务
  • 产品
  • 解决方案
  • 应用商城
  • 合作伙伴
  • 开发者
  • 支持与服务
  • 了解天翼云
      • 文档
      • 控制中心
      • 备案
      • 管理中心

      spring prototype bean 获取处理

      首页 知识中心 其他 文章详情页

      spring prototype bean 获取处理

      2023-06-28 09:05:35 阅读次数:83

      prototype,spring

      When to use prototype beans?

      Before we fall into the pitfalls of injecting prototype into singleton beans, stop for a moment to think when you actually need such relation.

      Just because you use dependency injection in your project, it doesn’t mean you should avoid the new keyword like the plague. There is nothing wrong if you instantiate a stateful object on your own.

      Usually, we use the prototype scope for a stateful object when it has dependencies on other Spring beans. Why? Because the framework will autowire these dependencies for us.

      Let’s see this case in a practicle sample.

      Prototype in singleton bean example

      Now consider the following compoistion of Spring beans.

      spring prototype bean 获取处理

       

       

       

      Let’s start with the right side of the diagram where a prototype bean depends on a singleton. No matter how many instances of MessageBuilders Spring creates, we expect they will always get the reference to the same ContentProcessor object. This part is easy.

      Next, the left side. By contrast, here a singleton bean depends on a prototype. When Spring creates the MessageService bean, it will also create a single instance of MessageBuilder. But just one. That’s all MessageService needs to be created.

      But hang on a minute.

      For this particular graph of objects, Spring creates only one instance for each bean definition. Even though one of them is a prototype. If we had another bean depending on MessageBuilder, it would get another instance of the prototype bean. But in this case, Spring creates only one.

      So what if you want a new instance of the prototype bean on every call to a particular method of the singleton bean? Not only when Spring creates this singleton?

      Don’t worry. There’re multiple solutions.

      You will see all possible options in a moment. But before I share them with you, we need a sample dependency between a prototype and a singleton for demonstration purpose.

      Prototype in singleton dependency demo

      We need a prototype, a singleton which depends on the prototype, and an automated test to verify the number of prototype instances.

      Let’s write each step by step.

      Prototype with instance counter

      First, the prototype.

      We want to know how many objects the Spring framework creates. We’re going to use a simple static counter incremented in the class constructor.

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      @Service
      @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
      class MessageBuilder {
       
          private static final AtomicInteger instanceCounter = newAtomicInteger(0);
       
          MessageBuilder() {
              instanceCounter.incrementAndGet();
          }
       
          static int getInstanceCounter() {
              return instanceCounter.get();
          }
       
      }

      We need the counter only for testing. The main task of the class is to build some immutable Message object. Our prototype will use the Builder pattern as presented below.

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      class MessageBuilder {
       
          //...
          private String content;
          private String receiver;
       
          MessageBuilder withContent(String content) {
              this.content = content;
              return this;
          }
       
          MessageBuilder withReceiver(String receiver) {
              this.receiver = receiver;
              return this;
          }
       
          Message build() {
              return new Message(content, receiver);
          }
       
      }

      Singleton dependent on prototype bean

      Next, the singleton implementation.

      The MesssageService class is a simple singleton with only one method. It calls all three methods of the prototype.

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      @Service
      class MessageService {
       
          private final MessageBuilder messageBuilder;
       
          MessageService(MessageBuilder messageBuilder) {
              this.messageBuilder = messageBuilder;
          }
       
          Message createMessage(String content, String receiver) {
              return messageBuilder
                      .withContent(content)
                      .withReceiver(receiver)
                      .build();
          }
       
      }

      As a reminder, since Spring 4.3 you do not have to put the @Autowired annotation on a constructor if there is only one in a class. The framework uses it automatically.

      Checking prototype instance count

      Finally, we write a test that will confirm that on every call to the singleton, Spring creates a new prototype instance. That’s our goal. We call the singleton twice so we expect two objects.

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      @RunWith(SpringRunner.class)
      @SpringBootTest
      public class MessageServiceTest {
       
          @Autowired
          private MessageService messageService;
       
          @Test
          public void shouldCreateTwoBuilders() throws Exception {
              //when
              messageService.createMessage("text", "alice");
              messageService.createMessage("msg", "bob");
              //then
              int prototypeCounter = MessageBuilder.getInstanceCounter();
              assertEquals("Wrong number of instances", 2, prototypeCounter);
          }
       
      }

      Now we’re ready to examine all possible solutions to inject prototype bean into a singleton.

      How to inject prototype bean into singleton bean?

      When you work with a prototype bean in a singleton, you have three options to get a new instance of the prototype:

      1. Spring can autowire a single prototype instance when it creates the singleton. It’s the default framework behavior.
      2. Spring can create a new prototype instance on every call to any method of this prototype.
      3. You can programmatically ask the Spring context to create a new prototype instance at the moment you need a new object.

      Option 1: Injecting on singleton construction

      As I already mentioned, injecting on construction is default behavior of the framework. If a singleton bean depends on a prototype, Spring creates a single prototype instance dedicated for this particular singleton.

      The singleton resuses its single prototype instance through its whole lifecycle.

      Let’s run the test we wrote in the previous paragraph and confirm that Spring creates only one prototype.

      spring prototype bean 获取处理

       

       

       

      Option 2: Injecting on prototype method call

      Another possibility is to force Spring to create a new prototype instance when every call on prototype’s method.

      To achieve this, you need to modify the prototype bean and set its proxy mode. You can do this by modifying the @Scope annotation as follows:

      1
      2
      3
      4
      5
      6
      @Service
      @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE,
             proxyMode = ScopedProxyMode.TARGET_CLASS)
      class MessageBuilder {
        // ...
      }

      By default, Spring doesn’t create a proxy object for a bean and uses the reference to the real bean when injection occurs. However, when you change the proxy mode, Spring creates and injects a special proxy object instead of the real object. The proxy decides on its own when to create the real object.

      spring prototype bean 获取处理

       

       

       

      By setting the proxy mode to ScopedProxyMode.TARGET_CLASS, Spring will create a new instance of the prototype whenever you call its method.

      What is the outcome of our test?

      spring prototype bean 获取处理

       

       

       

      We didn’t get one instance, as without the proxy, but as many as six.

      Why that happened?

      In our test, we call the createMessage() method on the MessageService object twice and this, in turn, executes three methods of the proxied MessageBuilder. Two times three gives us six in total and that is what our test proved.

      However, that is not what we wanted and it is even worse. Not only got we more instance than we expected, but also the final result is different than wanted because each instance has a separate state.

      The createMessage() method relies on the state that is stored between sequential calls on the prototype. With the given setup, the state is lost on every call to prototype methods. Therefore, setting a proxy mode is a dead end for our problem.

      Option 3: Creating prototype on demand with ObjectFactory

      The last option is the most flexible because it allows you to create a new prototype instance manually. Thanks to bean definition, Spring knows how to create a prototype. You just need to tell the framework when to do it.

      That’s when ObjectFactory comes in.

      ObjectFactory is a functional interface from Spring framework designed to provide a reference to beans managed by the application context. The interface defines only one method which returns an instance of the selected bean.

      How to use ObjectFactory with prototype beans?

      It’s very simple. You just need to define a dependency on the ObjectFactory for the chosen bean. Spring will generate and inject the appropriate implementation of the interface.

      Let’s update the MessageService singleton to see the factory in action.

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      @Service
      class MessageService {
       
          private final ObjectFactory<MessageBuilder> messageBuilder;
       
          MessageService(ObjectFactory<MessageBuilder> messageBuilder) {
              this.messageBuilder = messageBuilder;
          }
       
          Message createMessage(String content, String receiver) {
              return messageBuilder.getObject()
                      .withContent(content)
                      .withReceiver(receiver)
                      .build();
          }
       
      }

      Thanks to ObjectFactory you can create a prototype instance exactly when you need it.

      If we run our test again, it will pass. Every call to the createMessage() method gets its own instance of the prototype.

      spring prototype bean 获取处理

      ObjectFactory in unit test

      One of the reasons to use dependency injection is to simplify unit testing. It’s really simple to replace a real dependency with a stub or a mock.

      Because ObjectFactory is a function interface, you can easily write its stub implementation with the lambda expression.

      1
      2
      3
      4
      5
      6
      @Test
      public void shouldStubFactory() throws Exception {
          ObjectFactory<MessageBuilder> factory = () -> new MessageBuilder()
          MessageService sut = new MessageService(factory);
          //...
      }

      A few words of conclusion

      At this point, you should know about all the possible options for creating prototype beans. You learned that injecting a prototype bean into singleton may be a bit tricky. After reading the article, you know which injecting option is best for your requirements.

      Do you like the post and find it useful? Consider subscribing to my site. I’ll let you know about similar topics.

      版权声明:本文内容来自第三方投稿或授权转载,原文地址:https://blog.51cto.com/rongfengliang/3653905,作者:rongfengliang,版权归原作者所有。本网站转在其作品的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如因作品内容、版权等问题需要同本网站联系,请发邮件至ctyunbbs@chinatelecom.cn沟通。

      上一篇:spring上传

      下一篇:drill java && spring jdbc 连接使用

      相关文章

      2025-05-08 09:03:21

      基于spring+jsp+mysql实现的Java web论坛系统【源码+数据库+指导运行】

      本项目是一套基于spring+jsp+mysql实现的Java web论坛系统,主要针对计算机相关专业的正在做毕设的学生与需要项目实战练习的Java学习者。

      2025-05-08 09:03:21
      Java , jsp , spring , 功能 , 源码
      2025-05-08 09:03:07

      spring Bean的作用域和生命周期

      spring Bean的作用域和生命周期

      2025-05-08 09:03:07
      Bean , method , spring , 作用域 , 配置文件
      2025-05-07 09:08:54

      springboot系列教程(十二):基于转账案例,演示事务管理操作

      springboot系列教程(十二):基于转账案例,演示事务管理操作

      2025-05-07 09:08:54
      spring , 事务 , 接口 , 管理器 , 配置
      2025-04-14 08:48:01

      Java注解实现之how to use path variable @PathVariable

      Java注解实现之how to use path variable @PathVariable

      2025-04-14 08:48:01
      Java , spring
      2025-04-14 08:45:36

      Java SpringBoot 应用使用命令行 mvn spring-boot run 启动的原理

      将应用程序打包为 jar 并使用嵌入式 HTTP 服务器的最大优势之一是可以像运行其他任何应用程序一样运行这些提供了 Web 功能的应用程序。 调试 Spring Boot 应用程序也很容易; 不需要任何特殊的 IDE 插件或扩展。

      2025-04-14 08:45:36
      jar , spring , 应用程序
      2025-04-09 09:11:38

      spring boot设置session超时时长(自定义spring boot session超时时长)

      spring boot设置session超时时长(自定义spring boot session超时时长)

      2025-04-09 09:11:38
      boot , session , spring , 设置 , 超时
      2025-04-01 10:16:07

      JS之原型以及原型链

      JS之原型以及原型链

      2025-04-01 10:16:07
      prototype , 代码 , 函数 , 原型 , 属性 , 构造函数 , 查找
      2025-03-28 07:42:34

      关于数组的那些事

      关于数组的那些事

      2025-03-28 07:42:34
      prototype , 元素 , 函数 , 回调 , 数组 , 返回
      2025-03-25 08:08:59

      spring boot项目设置默认访问路径(页面)方法,包括spring boot 2.0及以上版本实现方法

      spring boot项目设置默认访问路径(页面)方法,包括spring boot 2.0及以上版本实现方法

      2025-03-25 08:08:59
      boot , spring , 代码 , 访问 , 页面 , 默认
      2025-03-25 08:08:18

      spring boot整合mybatis和hikariCP时遇到 jdbcUrl is required with driverClassName 错误的解决方法

      spring boot整合mybatis和hikariCP时遇到 jdbcUrl is required with driverClassName 错误的解决方法

      2025-03-25 08:08:18
      jdbc , spring , url , 数据库 , 数据源 , 配置文件
      查看更多
      推荐标签

      作者介绍

      天翼云小翼
      天翼云用户

      文章

      33561

      阅读量

      5242130

      查看更多

      最新文章

      spring boot设置session超时时长(自定义spring boot session超时时长)

      2025-04-09 09:11:38

      spring学习(ApplicationContext与BeanFactory实例化对象的基本流程与区别)(Bean工厂与IOC容器)(spring-IOC思想)

      2025-01-06 08:42:37

      spring+mybatis启动NoClassDefFoundError异常分析三部曲之二:定位错误

      2024-11-20 09:46:57

      spring boot 自定义过滤器链

      2024-11-05 08:30:44

      Maven 再学习之 bom 与 parent pom

      2024-09-25 10:14:48

      服务注册与发现

      2024-09-25 10:14:48

      查看更多

      热门文章

      axios&spring前后端分离传参规范总结

      2023-05-22 08:09:06

      Bean的作用域

      2023-06-07 07:31:19

      Content type ‘application/x-www-form-urlencoded;charset=UTF-8‘ not supported错误的多种解决方法及说明Content-Type

      2024-09-25 10:14:21

      [spring学习]10、AOP思想提出

      2024-09-25 10:13:34

      [手写spring](5)实现AOP机制(完结)

      2023-07-03 09:13:10

      nested exception is org.apache.ibatis.type.TypeException: Could not set parameters for mapping错误的决方法

      2024-09-25 10:14:21

      查看更多

      热门标签

      linux java python javascript 数组 前端 docker Linux vue 函数 shell git 节点 容器 示例
      查看更多

      相关产品

      弹性云主机

      随时自助获取、弹性伸缩的云服务器资源

      天翼云电脑(公众版)

      便捷、安全、高效的云电脑服务

      对象存储

      高品质、低成本的云上存储服务

      云硬盘

      为云上计算资源提供持久性块存储

      查看更多

      随机文章

      SSH整合jar包总结

      [spring学习]13、声明式事务(@Transaction)

      class java.time.LocalDateTime cannot be cast to class java.util.Date

      Failed to instantiate [java.lang.Long]: No default constructor found;nested exception is java.lang()

      eclipse安装STS插件遇到的问题

      [springMVC学习]11、自定义拦截器

      • 7*24小时售后
      • 无忧退款
      • 免费备案
      • 专家服务
      售前咨询热线
      400-810-9889转1
      关注天翼云
      • 旗舰店
      • 天翼云APP
      • 天翼云微信公众号
      服务与支持
      • 备案中心
      • 售前咨询
      • 智能客服
      • 自助服务
      • 工单管理
      • 客户公告
      • 涉诈举报
      账户管理
      • 管理中心
      • 订单管理
      • 余额管理
      • 发票管理
      • 充值汇款
      • 续费管理
      快速入口
      • 天翼云旗舰店
      • 文档中心
      • 最新活动
      • 免费试用
      • 信任中心
      • 天翼云学堂
      云网生态
      • 甄选商城
      • 渠道合作
      • 云市场合作
      了解天翼云
      • 关于天翼云
      • 天翼云APP
      • 服务案例
      • 新闻资讯
      • 联系我们
      热门产品
      • 云电脑
      • 弹性云主机
      • 云电脑政企版
      • 天翼云手机
      • 云数据库
      • 对象存储
      • 云硬盘
      • Web应用防火墙
      • 服务器安全卫士
      • CDN加速
      热门推荐
      • 云服务备份
      • 边缘安全加速平台
      • 全站加速
      • 安全加速
      • 云服务器
      • 云主机
      • 智能边缘云
      • 应用编排服务
      • 微服务引擎
      • 共享流量包
      更多推荐
      • web应用防火墙
      • 密钥管理
      • 等保咨询
      • 安全专区
      • 应用运维管理
      • 云日志服务
      • 文档数据库服务
      • 云搜索服务
      • 数据湖探索
      • 数据仓库服务
      友情链接
      • 中国电信集团
      • 189邮箱
      • 天翼企业云盘
      • 天翼云盘
      ©2025 天翼云科技有限公司版权所有 增值电信业务经营许可证A2.B1.B2-20090001
      公司地址:北京市东城区青龙胡同甲1号、3号2幢2层205-32室
      • 用户协议
      • 隐私政策
      • 个人信息保护
      • 法律声明
      备案 京公网安备11010802043424号 京ICP备 2021034386号