我正在考虑@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/