We’re using Scala with Spring Boot, so creating Singleton objects is as simple as using the Scala ‘object’ keyword instead of the ‘class’ keyword, and filling it with whatever functions are needed. So far, it seems that Singleton objects can do the same thing as @Service classes, and also has the extra benefit of avoiding circular dependency errors during dependency injection. Is there any reason to use @Service classes over Singletons?
Asked
Active
Viewed 2,386 times
2
-
1How do you mock `object`s? That's way easier to have classes for mocking them in tests. – Gaël J Nov 10 '21 at 18:35
-
Also how do you swap implementations with `object`s? – Gaël J Nov 10 '21 at 18:37
-
This is roughly the same question as "static classes versus singleton" in plain Java. See for instance: https://stackoverflow.com/questions/3714971/difference-between-singleton-class-and-static-class – Gaël J Nov 10 '21 at 18:38
1 Answers
3
Annotating classes with @Service
means that a Spring-managed bean will be created for such classes. By default, they are also singletons. However, being Spring-managed beans make it possible to use Spring-related features, such as:
- Dependency injection (being this bean injected in other Spring-managed beans and also inject other Spring-managed beans into this one);
- Spring AOP (allowing, for example, the usage of
@Transactional
); - Application context changes awareness (you could make your
@Service
implementApplicationListener
so that you can do something based on Application related events); - etc...

João Dias
- 16,277
- 6
- 33
- 45