java - 为什么我们在 Spring Boot 中需要原型(prototype)范围

标签 java spring-boot

我正在考虑@scope("prototype")范围,但我不明白,因为我们已经有了 new关键词。它们都在运行时创建对象的新实例。使用prototype有什么好处? ?重新分配比使用 new 更容易吗? ?当我使用 new 创建新对象时,我做错了什么吗?关键字?

我正在尝试了解它的优点。

我发现了这个问题,但它没有解释 new 的优点/缺点和prototype :What is the difference between bean with scope prototype and new Object in singleton bean?

最佳答案

通过使用 new关键字您正在创建一个java对象,但它不是一个spring bean,并且不会出现在spring容器中。但如果你使用@scope("prototype")对于每个请求,都会提供一个新的 Spring Bean 。了解更多information

什么是 Spring Bean ?

A Spring bean is basically an object managed by Spring. More specifically, it is an object that is instantiated, configured and otherwise managed by a Spring Framework container. Spring beans are defined in a Spring configuration file (or, more recently, by using annotations), instantiated by the Spring container, and then injected into your application.

Spring Bean 的优点?

1) 默认情况下,所有 spring bean 都是不可变的,spring IOC 容器将管理它们

2)通过使用依赖注入(inject),您可以轻松地将bean注入(inject)任何其他对象

3) 依赖注入(inject)使测试更容易。注入(inject)可以通过构造函数完成。

4) 如果您使用 spring boot然后你可以注入(inject) application.yml 中的值或application.properties使用 @Value 进入 Spring Bean 注释

关于java - 为什么我们在 Spring Boot 中需要原型(prototype)范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58086527/

相关文章:

java - Spring批处理条件步骤,未正确执行

spring-boot - 如何实现动态@ConfigurationProperties 前缀

java - 如何在 Android 中通过 MediaStore API 检索和打开保存到下载的 PDF 文件?

java - drawPolyline() 无法正确绘制

java - 使用 jpa 通过 spring boot 进行分页

java - 当我自定义 addCorsMappings() 时,在 Json 中转换 java-object (dto) 期间,转换日期会中断

java - 在 netbeans 中附加调试器是什么意思?

java - 如何在Java中设置语言?

java - 用于存储key-value-value等元素的集合

spring-boot - flyway 5.2.4如何升级到9.0.1?