How to Share DTO Across Spring Boot Microservices?
Last Updated :
28 May, 2024
A Data Transfer Object(DTO) is an object that encapsulates data and transports it from one subsystem of an application to another. The Services layer in an N-Tier application often uses DTOs to transport data between itself and the UI Microservices have gained popularity over time. They are lighter, more modular, and easier to install and scale. However, Microservice designs present certain issues. Microservices have particular responsibilities. Multiple Microservices can be required to work together on completing an application workflow or activity.
Steps to Share DTO Across Java Microservices
Below are the steps to Share DTO Across Microservices.
Step 1: Connect DTO Across Microservices
The layer connects the two classes and uses a mapper component to transfer data from one side to the other and vice versa.
Java
@RestController
@RequestMapping("/users")
class UserController {
private UserService myUserService;
private RoleService myRoleService;
private Mapper myMapper;
// Constructor
@GetMapping
@ResponseBody
public List<UserDTO> getUsers() {
return myUserService.getAll()
.stream()
.map(myMapper::toDto)
.collect(Collectors.toList());
}
@PostMapping
@ResponseBody
public UserIdDTO createUser(@RequestBody UserCreationDTO userCreationDTO) {
User user = myMapper.toUser(userCreationDTO);
userCreationDTO.getRoles()
.stream()
.map(role -> myRoleService.getOrCreate(role))
.forEach(user::addRole);
myUserService.save(user);
return new UserIdDTO(user.getId());
}
}
Step 2: Share DTO Between Microservices
Consider how a consumer orders a product. This procedure is based on the Customer-Order model. Check the process from the perspective of the service architecture.
{
// Order details
"order": {
// Customer ID associated with the order
"customerId": 2,
// Item ID of the product being ordered
"itemId": "F2521"
}
}
Step 3: Use Order Service for communication
The User Service transforms its internal user objects into UserDTO objects and transmits them as payloads when it has to interact with the Order Service.
Java
public class UserService {
public UserDTO getUserById(String userId) {
User user = userRepository.findById(userId);
// Convert User to UserDTO
UserDTO userDTO = new UserDTO();
userDTO.setUserId(user.getUserId());
userDTO.setUsername(user.getUsername());
userDTO.setEmail(user.getEmail());
return userDTO;
}
}
Step 4: Receive requests for Order Service
The Order Service expects a UserDTO object and, if required, transforms it back to its internal representation when it gets a request containing user data from the User Service or any other client.
Java
public class OrderService {
public void placeOrder(UserDTO userDTO, OrderDTO orderDTO) {
// Convert UserDTO to internal User object if needed
User user = new User();
user.setUserId(userDTO.getUserId());
user.setUsername(userDTO.getUsername());
user.setEmail(userDTO.getEmail());
// Process order
// ...
}
}
Step 5: Add certain information
A microservice needs certain information from other services to complete any request. Assume there is a third microservice that handles order payment requests. All variables have getters and setters specified to offer access to and modify their values. Unlike the Order service, this service needs different consumer information:
Java
public class CustomerDTO {
private String firstName;
private String lastName;
private String cardNumber;
public CustomerDTO(String firstName, String lastName, String cardNumber) {
this.firstName = firstName;
this.lastName = lastName;
this.cardNumber = cardNumber;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getCardNumber() {
return cardNumber;
}
public void setCardNumber(String cardNumber) {
this.cardNumber = cardNumber;
}
}
Step 6: Use the RestTemplate object
The following section of code shows how to invoke a RESTful service during the order-generating process. The variables have been renamed to improve readability and offer a better ownership explanation.
Java
// Original code snippet
String serviceUrl = "http://localhost:8002/order-service";
OrderResponse orderResponse = restTemplate.postForObject(serviceUrl + "/create",
request, OrderResponse.class);
// Modified code snippet with explanation
String myServiceUrl = "http://localhost:8002/order-service";
OrderResponse myOrderResponse = restTemplate.postForObject(myServiceUrl + "/create",
myRequest, OrderResponse.class);
- myServiceUrl is the variable that contains the URL for the service endpoint where the request is being submitted. Prefixing it with "my" helps to show that it is particular to this class/method.
- myOrderResponse variable stores the response that the service provided following a POST request. Prefixing it with "my" indicates that it's tied to this class or function.
Similar Reads
Auto-Scaling Microservices with Eureka and Spring Boot Auto-scaling Microservices with Eureka and Spring Boot involves leveraging Eureka for the service discovery and Spring Boot for building microservices that can dynamically scale based on the demand. This setup allows for efficient resource utilization and it can ensure that the system can handle var
7 min read
Introduction to Messaging Queues in Spring Boot Microservices In Microservices architecture, communication between the services is essential for achieving loose coupling and scalability. Messaging queues provide a reliable and asynchronous communication mechanism that can enable the seamless interaction between the microservices. Spring boot is a popular frame
8 min read
Java Spring Boot Microservices - Developing Service Discovery In Microservices, Service Discovery helps us by providing a database of available service instances so that services can be discovered, registered, and de-registered based on usage. For a detailed explanation of Service Discovery please refer to this article Service Discovery and Service Registry in
3 min read
Best Way to Master Java Spring Boot Microservices â A Complete Roadmap The World is Moving Towards Microservices Architecture. Yes, it's true but why? Microservices are becoming more popular day by day. To know Why the World is Moving Towards Microservices Architecture you must refer to this article. This will give you a complete idea of why big organizations like Goog
6 min read
Microservices Communication with Apache Kafka in Spring Boot Apache Kafka is a distributed streaming platform and can be widely used to create real-time data pipelines and streaming applications. It can publish and subscribe to records in progress, save these records in an error-free manner, and handle floating records as they arrive. Combined with Spring Boo
6 min read
How to Use AWS Secrets Manager in Spring Boot? AWS secret manager is most popular AWS service used for storing service secrets and other environment variables used for deploying applications. Spring applications use most of the variables defined in the application.properties file. In this article, we will see how to use AWS secret manager in Spr
4 min read
Spring Cloud - How to Register Microservices Using Netflix Eureka? Service Discovery is one of the major things of a microservice-based architecture. Eureka is the Netflix Service Discovery Server and Client. The server can be configured and deployed to be highly functional, with each server copying the state of the registered services to the others. In this articl
4 min read
Spring Cloud - How to Discover Microservice using Netflix Eureka Spring Cloud is a collection of projects like load balancing, service discovery, circuit breakers, routing, micro-proxy, etc will be given by Spring Cloud. So spring Cloud basically provides some of the common tools and techniques and projects to quickly develop some common patterns of the microserv
11 min read
Properties with Spring and Spring Boot Java-based applications using the Spring framework and its evolution into the Spring Boot and the properties play a crucial role in configuring the various aspects of the application. Properties can allow the developers to externalize the configuration settings from the code. Understanding how to wo
4 min read
Spring Boot - How to set a Request Timeout for a REST API In Microservice architecture, there are multiple microservices available for an application. For the application to work properly necessary services need to communicate with each other. There can be communication of messaging type or REST calls. How does REST API Work?In REST Calls the process is sy
6 min read