Spring Framework Singleton vs Singleton Design Pattern

Spring Framework Singleton vs Singleton Design Pattern

Singleton != Singleton

The singleton pattern is a very popular design patterns in object-oriented programming. The Spring Framework allows for beans defined in many ways. The most common and default way is for beans to be singletons. Yet, there is a significant difference between the singleton pattern and Spring's implementation. Let's breakdown what that difference looks like.

The Singleton Design Pattern Explained

The Gang of Four singleton design pattern can be summarized down to:

  • private static field instance
  • private constructor
  • public static getter

image.png

How Spring implements the Singleton Pattern

The Spring Framework is a collection of projects that have an opinionated way of developing production-ready Java-based applications. One of the very first concepts you're introduced to when you begin working with Spring is the bean. Simply put, a bean is an object that Spring manages. There are different bean scopes, which define the lifecycle of a bean. By default a bean is scoped as a singleton.

image.png

The Major Difference

In Spring you can have many instances of the same type of bean. One way to do this is by having different methods names for each of your Spring beans.

image.png

The same object type but if you were to to inspect these objects you would see they are separate instances.

Compare that with the singleton design pattern implementation. You will notice that many instances is not possible with our implementation. Which is because the constructor is private and we are only initializing the object once.

In Conclusion

The singleton design pattern and the one implemented in Spring are different. If you're new to Spring and familiar with the singleton pattern, that can be a little confusing. I hope this has helped make these concepts clearer.

If you like what you've read, want to continue the discussion, or have anything else on your mind, reach out to me on Twitter with your thoughts on the subject.