We've already built basic apps with Spring Boot, looked into the Spring Boot project structure, its auto-configuration, and ways to configure it via application.properties and application.yml. Now we're ready to take the next step and use Spring Boot to build microservices.
Why Spring Boot solves problems
Before diving into hands-on stuff, let's understand why Spring Boot is so popular for developing microservices. If you've ever suffered through endless XML configs in old Spring apps or spent hours chasing the correct dependency version, you'll definitely appreciate what Spring Boot brings to the microservices table.
Simplifying development and configuration
Spring Boot gives you powerful tools to make development easier:
- Auto-configuration: most of the necessary setup is done automatically, which dramatically reduces the time to "assemble" an app.
- Spring Boot Starters: these are opinionated dependency bundles for common features. For example,
spring-boot-starter-webgives you everything you need for a REST API, andspring-boot-starter-data-jpa— for DB work. - Embedded web servers: Tomcat, Jetty or Undertow so you don't have to deploy to an external server.
Support for microservices architecture
Microservices need isolation, modularity, easy scaling, and the ability to quickly add new components. Spring Boot makes this simpler thanks to:
- The "opinionated configuration" concept: Spring Boot offers ready-made settings that work out of the box.
- Compatibility with DevOps ecosystems: e.g. integrations with Docker or Kubernetes.
- Broad integration support: working with databases, message brokers (like Kafka), centralized configuration, and other microservice concerns.
Building your first microservice app with Spring Boot
Now that we know why to use Spring Boot for microservices, let's create our first app. For example, we'll build a client management service (CustomerService) that provides basic CRUD functionality.
Project setup
1. Create the project via Spring Initializr
Open Spring Initializr and configure:
Project: Maven or Gradle (pick whichever you're more comfortable with).Dependencies: addSpring WebandSpring Data JPA.Language: Java.Packaging: Jar.Java Version: 17 (or your current version).
Then download the project and open it in your favorite IDE (for example, IntelliJ IDEA or Eclipse).
2. Project structure
After opening the project you'll see the basic structure:
src/main/java
└── com.example.customerservice
├── CustomerServiceApplication.java
└── ... (your classes will go here)
src/main/resources
├── application.properties
└── ... (resource files)
In the src/main/java directory we'll write the code, and in application.properties — the configs.
Implementing CustomerService
1. Data model: the Customer class
Create the Customer entity that will represent a customer.
package com.example.customerservice.model;
import jakarta.persistence.*;
@Entity // Indicates this is a JPA entity
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
// Getters and setters
public Long getId() {
return id;
}
public void setId(Long 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;
}
}
We used JPA annotations:
@Entityturns the class into a database entity.@Idand@GeneratedValuemark theidfield as the primary key with auto-generation.
2. Repository: CustomerRepository
Create an interface for data access.
package com.example.customerservice.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.customerservice.model.Customer;
public interface CustomerRepository extends JpaRepository<Customer, Long> {
}
Spring Data JPA will automatically generate all the methods for DB operations (for example, save, findAll, deleteById).
3. Controller: CustomerController
Create a REST API to manage customers.
package com.example.customerservice.controller;
import com.example.customerservice.model.Customer;
import com.example.customerservice.repository.CustomerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/customers")
public class CustomerController {
@Autowired
private CustomerRepository customerRepository;
@GetMapping
public List<Customer> getAllCustomers() {
return customerRepository.findAll();
}
@PostMapping
public Customer createCustomer(@RequestBody Customer customer) {
return customerRepository.save(customer);
}
@DeleteMapping("/{id}")
public void deleteCustomer(@PathVariable Long id) {
customerRepository.deleteById(id);
}
}
Here we created three endpoints:
GET /customers: get all customers.POST /customers: create a new customer.DELETE /customers/{id}: delete a customer.
Running and testing
- Database setup
Add H2 settings toapplication.properties(an in-memory DB so you don't have to worry about setup at the start):spring.datasource.url=jdbc:h2:mem:testdb spring.datasource.driver-class-name=org.h2.Driver spring.datasource.username=sa spring.datasource.password=password spring.jpa.database-platform=org.hibernate.dialect.H2Dialect - Start the application
Run theCustomerServiceApplicationclass (it contains themainmethod). The app will start at http://localhost:8080. - Test the API
Use Postman or cURL:
- Get customers:
curl -X GET http://localhost:8080/customers - Create a customer:
curl -X POST http://localhost:8080/customers -H "Content-Type: application/json" -d '{"name":"John Doe","email":"john.doe@example.com"}'
Spring Boot perks for microservices
Now we have a working microservice! But Spring Boot offers a lot more cool features:
- Easy scaling: each microservice is an independent app you can run separately.
- Easy integration with Kafka, API Gateway and other tools (we'll cover this in future lectures).
- Convenient config via
application.yml: topics like multi-profile configs and environment management will be discussed in upcoming lectures.
At this stage you have a basic idea of how Spring Boot helps you quickly build a functional microservice.
GO TO FULL VERSION