top of page
Darshil Gadhiya

Singleton Pattern with Spring Boot

Singleton Pattern:

The singleton design pattern is a creational design pattern which restricts class instantiation to a single instance. This is beneficial when a single component is required to coordinate actions across the system. For example, if we have a logging class in our application, it makes acceptable to have only one instance that can be accessed from anywhere.


The Problem:

It takes time to create a database connection. It involves connecting to a network, authenticating, and performing additional setup tasks. Many sections of code in a typical enterprise program must communicate with the database, and it can be inefficient to establish a new database connection each time.


The Solution: Singleton Pattern

The Singleton pattern can be used to handle a single database connection that is reused throughout the program. This way, we only pay for the connection once.


Implementing the Singleton Pattern

We must first create the Singleton class. This class will contain a method to retrieve the single instance of the class as well as a private constructor.



The above code includes a private constructor that prevents the class from being instantiated. The 'getInstance()' method returns a single instance of the class, or creates one if none exists. The 'getConnection()' method is used to obtain a database connection.


Using the Singleton Class

Now, we can use our Singleton class in any other class in our application. Here’s an example:


In the 'UserService' class, we obtain an instance of our 'DatabaseConnectionManager' and utilize it to retrieve the database connection. The connection is able to be used to query the database.


Testing the Singleton Class



We retrieve and return a user from the database using the `UserService` in the `UserController`.

360 views0 comments

Recent Posts

See All

Battle of the Backends: Java vs Node.js

Comparing Java and Node.js involves contrasting two distinct platforms commonly used in backend development. Here’s a breakdown of their...

Comments


bottom of page