简体   繁体   中英

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). 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.

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. In Spring I use @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 . Many consider Singleton an anti-pattern and there's plenty of information out there on why. 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. 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.

Singleton is the default scope in Spring so you don't actually need to specify it. 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 . Please check the Spring documentation for more information on available scopes and their meaning.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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