0

I know Spring can create singleton beans. Does it mean that we needn't use 'Singleton Pattern' to create a java bean by myself? And what's the difference between the spring singleton and singleton pattern?

Guedes
  • 961
  • 9
  • 16
zhiping chen
  • 93
  • 1
  • 5

1 Answers1

1

Spring singleton is unique ApplicationContext (per Spring container) instance. Meaning if you create a new ApplicationContext then you would get a new instance of the bean even if it's singleton.

However original Java singleton means one instance per Classloader. Meaning that singleton instance remains same for a particular classloader. In most cases that's fine, however suppose if you need a true singleton, single instance per JVM then there's some extra work to do. Look at this example https://stackoverflow.com/a/47445573/5343269

Answer to your question is if you are instantiating a single spring container in your application then spring singleton bean can be treated as a singleton, however that's true only for Spring components. Meaning this instance can not be accessed by any class that's not a Spring bean.

To be safe, don't rely on the spring singleton and create your own singleton class.

11thdimension
  • 10,333
  • 4
  • 33
  • 71
  • Unless there are unique things about this question worth answering, it is better to flag as a duplicate. Some excellent reasons for this have been discussed on meta: [Is it my responsibility to search for duplicates & vote to close before answering?](https://meta.stackexchange.com/questions/91180/is-it-my-responsibility-to-search-for-duplicates-vote-to-close-before-answerin/105231#105231) – JonathanDavidArndt Nov 29 '17 at 01:25