Search code examples
springsingletonanti-patterns

Is Singleton an Anti-pattern?


Is Singleton an anti-pattern? If yes, then Dependency Injection in Spring also Anti-pattern (because Spring promotes Singleton bean which is default)?


Solution

  • There's an important difference between hard-coding a singleton and using Spring to create a singleton bean: the latter is just configuration.

    As such Spring doesn't prevent testability: it's a single use-case where a bean is used as a singleton. You can easily use the same spring by manually instantiating it in a test, or replacing it with a mocked implementation of the same interface.

    If you code a class as a singleton then you can't easily replace it, without rewriting it. Testing is just a single example where you might want to replace it. If you realize that you'll need two different instances of that bean, then you're stuck with a hard-coded singleton as well.