关于 Grails 服务 Class 单例 属性

About Grails Service Class Singleton Property

我对 Grails 服务有点困惑 Class 单例 属性。正如我们所知,Grails 服务 Class 默认情况下是单例的。如果是这样,为什么它允许使用 new 关键字实例化 class 而没有任何错误?如果我们实例化服务 class,它会在每次调用时创建不同的对象吗?

Grails 服务的范围与 Spring 如何完成依赖注入有关。此范围仅影响注入的服务。

您可以任意多次实例化服务 class,并且每次都会创建一个新实例。框架不限制这个,也不应该限制这个。但是,您应该坚持依赖依赖注入来访问您的服务。

If it is so, why does it allow to instantiate the class without any error using the new keyword?

我们不会阻止您创建实例,但没有充分的理由这样做。您永远不应该 new 在应用程序中 class 启动 Grails 服务的实例。

If we instantiate the service class, does it create the different object on each call?

是的,但如上所述,您永远不应创建实例。

Grails 服务工件默认是单例的,这意味着创建 1 个实例并将其添加到 Spring 应用程序上下文。如果你想引用实例,你应该让 Spring 在你需要的地方注入实例,而不是自己创建实例。