How to use the Builder design pattern with Spring Boot



Most developers are aware of design patterns. But most of the time they struggle to use design patterns in enterprise applications practically.

The builder design pattern is a creational design pattern that can be used very efficiently in our applications. Here I am going to explain how to use the builder design pattern in our Spring Boot application using a generic scenario. If you need to get a basic idea about the Builder pattern, please refer to this, Builder Design pattern. In this article, I will explain the practical usage of the Builder pattern.

We can use this pattern to build the response entity object when we use ResponseEntity in RestControllers. If the response entity has more parameters, the builder pattern can be used to avoid using telescopic constructors. Here I created a response entity class which is called ApiResponse and I will use the builder pattern to create this class.



As you can see, the ApiResponse object has five attributes, httpHeaders, httpStatusCode, message, data and otherParams. To use this, I create another component called ResponseBuilder as below.



As you can see, the builder class contains overloaded methods with different parameters. This can be changed according to your business requirements. You can define what you expected.

Let’s see how to use this in the service layer. Before we jump into the service layer, Here is the RestController.



Here is the service class.



In the above endpoint, it requires HttpStatus code, a message and the data only. In the response builder, there is a matching method for the above details. I have already created an entity called Customer and a Repository called CustomerRepository. You can find the complete code at the end of this article.

Once you hit http://localhost:8090/api/v1/customers URL, you will be able to see the below response.


Since I didn’t use httpHeaders and other parameters, they are empty in the response. Even though I don’t have sample data, the data field is also empty.

The builder pattern can be used very easily in the service layer, you can define required data for the response or leave them empty without setting null.


The complete code can be found on GitHub.





How to use the Builder design pattern with Spring Boot How to use the Builder design pattern with Spring Boot Reviewed by Ravi Yasas on 1:33 AM Rating: 5

No comments:

Powered by Blogger.