简体   繁体   English

Spring Boot桌面/ CLI应用程序中组件的正确@Scope是什么?

[英]What is the correct @Scope for Components in Spring Boot desktop/CLI applications?

I've already written a couple of Spring Boot application (at the moment, one for web, one using JavaFX and a handful CLI applications). 我已经编写了几个Spring Boot应用程序(目前,一个用于Web,一个使用JavaFX和一些CLI应用程序)。 While all work as expected, I currently struggle with one particular concept of desktop or command line applications: The @Scope annotation for @Service s and @Component s. @Scope注解为@Service S和@Component S:虽然如预期所有的工作,我目前用的桌面或命令行应用程序的一个特定的概念奋斗。

I recently read a lot of why singletons are "evil" or at least undesired, but for desktop applications I currently see no other way to implement it, since most of the time a single instance is enough in these kinds of applications. 我最近阅读了很多为什么单身人士“邪恶”或至少不受欢迎,但对于桌面应用程序,我目前看不到其他方法来实现它,因为大多数时候单个实例在这些类型的应用程序中就足够了。

In Guice I would create an (non-static and non-final) instance in my module. Guice中,我将在我的模块中创建一个(非静态和非最终)实例。 In Spring I use @Scope("singleton") . Spring中我使用@Scope(“singleton”)

What I want to know now: Is this a clean solution? 我现在想知道的:这是一个干净的解决方案吗? Is there any other solution at all? 有没有其他解决方案?

Regards, Daniel 问候,丹尼尔

The articles you're reading are about the Singleton pattern . 您正在阅读的文章是关于Singleton 模式的 Many consider Singleton an anti-pattern and there's plenty of information out there on why. 许多人认为Singleton是一种反模式,并且有很多关于原因的信息。 See this answer for some good reasons on why you should avoid the pattern . 为什么你应该避免这种模式的一些很好的理由,请参阅这个答案

What you're referring to is singleton as a scope . 你所指的是单身作为范围 Spring does not follow the pattern, a scope of singleton simply indicates the container will only create a single instance and use that to satisfy dependencies. Spring不遵循模式,单例的范围只是表明容器只会创建一个实例并使用它来满足依赖关系。 There could be multiple containers each with it's own instance, or one container where the bean is singleton scope and another where it's prototype scope instead. 可能有多个容器,每个容器都有自己的实例,或者一个容器,其中bean是单例范围,另一个容器是原型范围。

Singleton is the default scope in Spring so you don't actually need to specify it. Singleton是Spring中的默认范围 ,因此您实际上不需要指定它。 If you don't have a specific reason to use a different scope then you probably want the default singleton. 如果您没有特定的理由使用不同的范围,那么您可能需要默认的单例。 Sometimes I need a bean to not be shared, in which case I may use prototype . 有时候,我需要一个bean 不能共享,在这种情况下,我可能会使用原型 Please check the Spring documentation for more information on available scopes and their meaning. 有关可用范围及其含义的更多信息,请查看Spring文档

In any case the key difference here is this is not an implementation of the singleton pattern. 在任何情况下,这里的关键区别是这不是单例模式的实现。 If Spring were to implement such a pattern then we would expect every container to have the same instance which is not the case at all. 如果Spring要实现这样的模式,那么我们希望每个容器都具有相同的实例 ,而实际情况并非如此。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM