1

Is it common that in Java programming using Spring bean to control singleton instance instead of making a class with the singleton pattern?

Bryan Fok
  • 3,277
  • 2
  • 31
  • 59

4 Answers4

4

It depends. If you need an utility class, which has no dependencies and that just provide a bunch of commons methods, I think it is quick and straightforward to build your own singleton.

But if you want to build a business class which needs to be injected with other dependencies, and probably, you want to define interfaces to avoid coupling between classes, I think Spring (or other DI frameworks) are better (easier) than build your own singleton.

malaguna
  • 4,183
  • 1
  • 17
  • 33
1

These are the differences :

  1. JVM handles the lifecycle of Singleton pattern classś object where Spring context handles life cycle of Spring singleton bean.

  2. Singleton pattern classś object will be single for whole JVM where if you have multiple SpringContext in same JVM you can have multiple objects of it.

Rajnikant Patel
  • 561
  • 3
  • 19
1

It depends on how loosely you interpret the Singleton pattern.

In my interpretation, Singleton implies that there is exactly one instance per given context. The context is usually the JVM (the ClassLoader, actually), as that is the easiest to implement with plain Java code, but nothing stops me from mapping the pattern to different contexts, one of them being Spring's ApplicationContext.

According to this definition, one could argue that the "request" and "session" scopes also hold singleton objects, just with a narrower scope.

See also this previous answer of mine, where I go into more detail.

Community
  • 1
  • 1
Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
0

Simply, when you use spring bean singleton, you will have one instance per spring container. However, when you implement the singleton pattern by yourself (java based design pattern in our case), you will have one instance per java class loader.

Katy
  • 1,023
  • 7
  • 19