0% found this document useful (0 votes)
45 views13 pages

Java Spring Boot Microservices Example - Step by Step Guide - Ge

This document provides a step-by-step guide for creating a simple microservice using Java Spring Boot. It covers the entire process from setting up a Spring Boot project to creating a MySQL database schema, defining entity classes, and implementing RESTful endpoints. The guide emphasizes the advantages of using Spring Boot for microservices development and includes code snippets for various components of the application.

Uploaded by

dilevod836
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
45 views13 pages

Java Spring Boot Microservices Example - Step by Step Guide - Ge

This document provides a step-by-step guide for creating a simple microservice using Java Spring Boot. It covers the entire process from setting up a Spring Boot project to creating a MySQL database schema, defining entity classes, and implementing RESTful endpoints. The guide emphasizes the advantages of using Spring Boot for microservices development and includes code snippets for various components of the application.

Uploaded by

dilevod836
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 13

Java Spring Boot Microservices Example –

Step by Step Guide


Last Updated : 02 Jan, 2025

Microservices is an architectural approach to build a collection of logic,


data layers, and loosely coupled applications. Every microservices
deals with one business function end-to-end independently from other
microservices. Microservices present simple and understandable APIs
to communicate with each other through lightweight common
protocols such as HTTP. With the increasing demand for Microservices
Architecture Patterns in the industry the popularity of Spring Boot is
also increasing because when it comes to Microservices Development
, Spring Boot is the first choice of every developer. Spring Boot is a
microservice-based framework that makes a production-ready
application in significantly less time. By using Spring Boot, you can
make your microservices smaller and it will run faster. For this reason,
Spring Boot has become the standard for Java microservices. In this
article, we will create a simple Microservice using Spring Boot.

Step-by-Step Guide
Step 1: Create a New Spring Boot Project in Spring Initializr

To create a new Spring Boot project, please refer to How to Create a


Spring Boot Project in Spring Initializr and Run it in IntelliJ IDEA . For
this project choose the following things

Project: Maven
Language: Java
Packaging: Jar
Java: 17

Please choose the following dependencies while creating the project.


Spring Boot DevTools
Spring Data JPA
MySQL Driver
Spring Web

Generate the project and run it in IntelliJ IDEA by referring to the above
article.

Note : We have used the MySQL database in this project.

Step 2: Create Schema in MySQL Workbench and Put Some Sample


Data

Go to your MySQL Workbench and create a schema named


gfgmicroservicesdemo and inside that create a table called employee
and put some sample data as shown in the below image. Here we have
created 4 columns and put some sample data.

1. id
2. name
3. email
4. age

Now we are going to fetch Employee Data from Employee Table in our
Spring Boot project. To do it refer to the following steps. Before moving
to IntelliJ IDEA let’s have a look at the complete project structure for
our Microservices.
Step 3: Make Changes in Your application.properties File

Now make the following changes in your application.properties file.

spring.datasource.url=jdbc:mysql://localhost:3306/gfgmicros
ervicesdemo
spring.datasource.username=put your username here
spring.datasource.password=put your password here

You may also refer to the below image:

Step 4: Create Your Entity/Model Class

Go to the src > main > java > entity and create a class Employee and
put the below code. This is our model class.

package com.gfg.employeaap.entity;

import jakarta.persistence.*;

@Entity
@Table(name = "employee")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;

@Column(name = "name")
private String name;

@Column(name = "email")
private String email;

@Column(name = "age")
private String age;

public int getId() {


return id;
}

public void setId(int id) {


System Design Tutorial
this.id What
= id;is System Design System Design Life Cycle High Level Design HLD
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public String getEmail() {


return email;
}

public void setEmail(String email) {


this.email = email;
}

public String getAge() {


return age;
}

public void setAge(String age) {


this.age = age;
}
}

Step 5: Create Your Repository Interface

Go to the src > main > java > repository and create an interface
EmployeeRepo and put the below code. This is our repository where we
write code for all the database-related stuff.

package com.gfg.employeaap.repository;
import com.gfg.employeaap.entity.Employee;
import org.springframework.data.jpa.repository.JpaRepository;

public interface EmployeeRepo extends JpaRepository<Employee,


Integer> {

Note : Please refer to this article to know more about


JpaRepository .

Step 6: Create an EmployeeResponse Class

Go to the src > main > java > response and create a class
EmployeeResponse and put the below code.

package com.gfg.employeaap.response;

public class EmployeeResponse {

private int id;


private String name;
private String email;
private String age;

public int getId() {


return id;
}

public void setId(int id) {


this.id = id;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public String getEmail() {


return email;
}

public void setEmail(String email) {


this.email = email;
}

public String getAge() {


return age;
}
public void setAge(String age) {
this.age = age;
}
}

Step 7: Create Your Service Class

Go to the src > main > java > service and create a class
EmployeeService and put the below code. This is our service class
where we write our business logic.

package com.gfg.employeaap.service;

import com.gfg.employeaap.entity.Employee;
import com.gfg.employeaap.repository.EmployeeRepo;
import com.gfg.employeaap.response.EmployeeResponse;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Optional;

public class EmployeeService {

@Autowired
private EmployeeRepo employeeRepo;

@Autowired
private ModelMapper mapper;

public EmployeeResponse getEmployeeById(int id) {


Optional<Employee> employee = employeeRepo.findById(id);
EmployeeResponse employeeResponse = mapper.map(employee,
EmployeeResponse.class);
return employeeResponse;
}

Step 8: Create an Employee Controller

Go to the src > main > java > controller and create a class
EmployeeController and put the below code. Here we are going to
create an endpoint ” /employees/{id} ” to find an employee using id.

package com.gfg.employeaap.controller;

import com.gfg.employeaap.response.EmployeeResponse;
import com.gfg.employeaap.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class EmployeeController {

@Autowired
private EmployeeService employeeService;

@GetMapping("/employees/{id}")
private ResponseEntity<EmployeeResponse>
getEmployeeDetails(@PathVariable("id") int id) {
EmployeeResponse employee =
employeeService.getEmployeeById(id);
return ResponseEntity.status(HttpStatus.OK).body(employee);
}

Step 9: Create a Configuration Class

Go to the src > main > java > configuration and create a class
EmployeeConfig and put the below code.

package com.gfg.employeaap.configuration;

import com.gfg.employeaap.service.EmployeeService;
import org.modelmapper.ModelMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class EmployeeConfig {

@Bean
public EmployeeService employeeBean() {
return new EmployeeService();
}

@Bean
public ModelMapper modelMapperBean() {
return new ModelMapper();
}

Note : You may refer to these two articles

Spring @Configuration Annotation with Example


Spring @Bean Annotation with Example
Before running the Microservice below is the complete pom.xml file.
Please cross-verify if you have missed some dependencies

<?xml version="1.0" encoding="UTF-8"?>


<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-
4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.gfg.employeaap</groupId>
<artifactId>employee-service</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>employee-service</name>
<description>Employee Service</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>3.1.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>

Step 10: Run Your Employee Microservice

To run your Employee Microservice src > main > java >
EmployeeServiceApplication and click on the Run button. If everything
goes well then you may see the following screen in your console.
Please refer to the below image.

Step 11: Test Your Endpoint in Postman

Now open Postman and hit the following URL:

GET: http://localhost:8080/employees/1

And you can see the following response:

{
"id": 1,
"name": "Amiya",
"email": "ar@gmail",
"age": "25"
}

Please refer to the below image:


This is how we have built our Employee Microservice with the help of
Java and Spring Boot. And you can also design all your endpoints and
write all the business logic, database logic, etc in the corresponding
files.

Comment More info Next Article


Spring Boot Microservices

Advertise with us
Communication using FeignClient
with Example

Similar Reads

Java Spring Boot Microservices Example - Step by Step Guide


Microservices is an architectural approach to build a collection of logic, data layers, and loosely
coupled applications. Every microservices deals with one business function end-to-end…

6 min read

Spring Boot Microservices Communication using FeignClient with Example


FeignClient also known as Spring Cloud OpenFeign is a Declarative REST Client in Spring Boot Web
Application. But what do you mean by Declarative REST Client? It means we need to specify the…

15 min read

Java Spring Boot Microservices - Develop API Gateway Using Spring Cloud…
The API Gateway Pattern in some cases stands for “Backend for frontend†. It is basically the
entry gate for taking entry into any application by an external source. The pattern is going on in a…

4 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…

3 min read

Best Way to Master Java Spring Boot Microservices – A Complete…


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…

6 min read

Java Spring Boot Microservices – Integration of Eureka and Spring Cloud…
Microservices are small, loosely coupled distributed services. Microservices architecture evolved as
a solution to the scalability, independently deployable, and innovation challenges with Monolithic…

5 min read

Debugging Eureka Issues in Spring Boot Microservices


Debugging Eureka issues in Spring Boot microservices involves several steps and checks to ensure
proper registration, discovery, and communication between services. Debugging the Eureka issues…

4 min read

Deploy Java Microservices on Amazon ECS using AWS Fargate


In recent, Microservices architecture has gained huge popularity. It provides an effective way to
develop and deploy applications. The Architecture of Microservices works on dividing a Monolithic…

10 min read

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…

8 min read

Spring Boot Kafka Producer Example


Spring Boot is one of the most popular and most used frameworks of Java Programming Language.
It is a microservice-based framework and to make a production-ready application using Spring Bo…

3 min read
Corporate & Communications
Address:
A-143, 7th Floor, Sovereign Corporate
Tower, Sector- 136, Noida, Uttar
Pradesh (201305)

Registered Address:
K 061, Tower K, Gulshan Vivante
Apartment, Sector 137, Noida,
Gautam Buddh Nagar, Uttar Pradesh,
201305

Advertise with us

Company Languages
About Us Python
Legal Java
Privacy Policy C++
In Media PHP
Contact Us GoLang
Advertise with us SQL
GFG Corporate Solution R Language
Placement Training Program Android Tutorial
GeeksforGeeks Community Tutorials Archive

DSA Data Science & ML


Data Structures Data Science With Python
Algorithms Data Science For Beginner
DSA for Beginners Machine Learning
Basic DSA Problems ML Maths
DSA Roadmap Data Visualisation
Top 100 DSA Interview Problems Pandas
DSA Roadmap by Sandeep Jain NumPy
All Cheat Sheets NLP
Deep Learning

Web Technologies Python Tutorial


HTML Python Programming Examples
CSS Python Projects
JavaScript Python Tkinter
TypeScript Web Scraping
ReactJS OpenCV Tutorial
NextJS Python Interview Question
Bootstrap Django
Web Design

Computer Science DevOps


Operating Systems Git
Computer Network Linux
Database Management System AWS
Software Engineering Docker
Digital Logic Design Kubernetes
Engineering Maths Azure
Software Development GCP
Software Testing DevOps Roadmap

System Design Inteview Preparation


High Level Design Competitive Programming
Low Level Design Top DS or Algo for CP
UML Diagrams Company-Wise Recruitment Process
Interview Guide Company-Wise Preparation
Design Patterns Aptitude Preparation
OOAD Puzzles
System Design Bootcamp
Interview Questions

School Subjects GeeksforGeeks Videos


Mathematics DSA
Physics Python
Chemistry Java
Biology C++
Social Science Web Development
English Grammar Data Science
Commerce CS Subjects
World GK

@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved

You might also like