什么时候在 Micronauts 中使用@Singleton 和@Prototype 合适?

When is it appropriate to use @Singleton and @Prototype in Micronauts?

我读了很多关于单例模式的坏话 (What is so bad about singletons?), however, @Singleton is used everywhere in this Micronaut doc to illustrate inversion of control https://docs.micronaut.io/1.3.0.M2/guide/index.html#ioc

什么时候使用@Singleton合适?例如,如果我有一个 UserInfoService,它有 getUserInfocreateUserInfoupdateUserInfo 方法,那么使用 @Singleton 是个好主意吗?

另一个单独的问题是我什么时候使用 @Prototype,因为如果我不对 function/class 使用任何注释,它不是默认的原型吗(就像我启动一个它在另一个 class/function) 中的新实例?

When is it appropriate to use @Singleton? For example, if I have a UserInfoService that has getUserInfo, createUserInfo, updateUserInfo method, is it a good idea to use @Singleton?

UserInfoService几乎可以肯定是无状态单例。

Another separate question is when do I use @Prototype, because if I don't use any annotation for a function/class, isn't it by default a prototype (as in I initiate a new instance of it in another class/function)?

如果您启动一个新实例,那么注解并不重要。注解只会影响 Micronaut 容器为您创建的实例。对于 @Singleton,容器创建单个实例并在所有需要它的注入点注入相同的实例。对于 @Prototype,容器为每个注入点创建一个新实例。

所有这些都是关于应用程序设计的,而不是关于 Micronaut 的。 Micronaut 提供了一种简单的机制,让您以声明方式表达(通过 @Singleton@Prototype)您是否希望共享同一实例,但问题实际上与应用程序设计有关。一般来说,你应该更喜欢无状态单例。如果出于某种原因您有一个必须是有状态的 bean,并且您有充分的理由不想共享来自不同上下文的实例,那么 @Prototype 可能是合适的。

希望对您有所帮助。

让我们 100% 清楚 GoF 单例设计模式和 @Singleton 注解是两个不同的东西。

请考虑单例设计模式要求您更改代码。您必须以防止多次实例化的方式编写代码。

另一方面,您可以将@Singleton注解添加到您喜欢的任何class,无需修改其代码以防止实例化;正如@Jeff-Scott-Brown 指出的那样,您可以通过简单地调用其构造函数来重复实例化此 Micronaut "Singleton"。

@Singleton 注释不会表现出您在 Singleton 设计模式中读到的那些负面后果,因为它没有实现 Singleton 设计模式。该术语在这里有两个不同的含义。

在相关说明中,@Prototype 注释也不遵循 GoF 原型设计模式。
Spring prototype following prototype design pattern

由于 Jeff Scott Brown 涵盖了您问题的大部分内容,因此您必须注意 Spring 中的 Singleton scope 之间的细微差别 单例模式

这两者之间的一些主要区别是

  • 单例模式确保每个特定 class 的一个实例 class 装载机。
  • Spring 单例是“每个容器每个 bean”。

希望对您有所帮助。