Building Microservices with Spring Boot (Basic Setup)


Table of Contents

  1. Introduction to Microservices
  2. Setting Up the Project Structure
  3. Creating the First Microservice
  4. Running the Microservice
  5. Configuring Application Properties
  6. Communicating Between Microservices
  7. Basic Service Discovery with Eureka
  8. Conclusion

1. Introduction to Microservices

Microservices architecture is an approach where an application is developed as a set of loosely coupled, independently deployable services. These services are built around business capabilities and are often organized around specific domains, with each service running in its own process and communicating with others via lightweight protocols such as HTTP or messaging queues.

Some key benefits of microservices include:

  • Scalability: Microservices allow for horizontal scaling, meaning individual services can be scaled based on demand.
  • Resilience: Failure in one service does not impact the entire application.
  • Independent Deployment: Microservices can be developed, deployed, and updated independently of one another.
  • Technology Agnostic: Each microservice can be written using the most appropriate technology stack for the specific service.

In this module, we’ll walk through building a basic microservice using Spring Boot and discuss some key concepts for creating microservices in a Spring ecosystem.


2. Setting Up the Project Structure

Before we start coding, let’s first set up the structure for our microservices application.

Step 1: Creating the Project

You can start by creating the project via Spring Initializr or your favorite IDE.

Go to Spring Initializr, and select the following options:

  • Project: Maven Project
  • Language: Java
  • Spring Boot Version: Choose the latest stable version
  • Group: com.example
  • Artifact: microservice-demo
  • Dependencies:
    • Spring Web
    • Spring Boot DevTools (for hot reloading)
    • Eureka Server (for service discovery)

Once you generate and unzip the project, open it in your IDE (such as IntelliJ or Eclipse).

Step 2: Directory Structure

Your project should have the following structure:

cssCopyEditmicroservice-demo/
    ├── src/
    ├── pom.xml
    ├── .gitignore
    └── README.md

3. Creating the First Microservice

Now let’s create a basic microservice that serves a simple RESTful endpoint.

Step 1: Create a RestController

In your project, navigate to the src/main/java/com/example/microservicedemo directory, and create a new class called HelloController.java.

javaCopyEditpackage com.example.microservicedemo;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @GetMapping("/hello")
    public String sayHello() {
        return "Hello from Spring Boot Microservice!";
    }
}

This controller exposes an endpoint /hello which returns a simple message.

Step 2: Main Application Class

Your MicroserviceDemoApplication.java will serve as the entry point for the application. It should look like this:

javaCopyEditpackage com.example.microservicedemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MicroserviceDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(MicroserviceDemoApplication.class, args);
    }
}

4. Running the Microservice

Step 1: Run the Application

You can run the application using your IDE or by executing the following command in the terminal:

bashCopyEditmvn spring-boot:run

Alternatively, you can run the application directly from the IDE by running the MicroserviceDemoApplication class.

Step 2: Accessing the Endpoint

Once the application is up and running, navigate to:

bashCopyEdithttp://localhost:8080/hello

You should see the response:

csharpCopyEditHello from Spring Boot Microservice!

5. Configuring Application Properties

Step 1: Configure Application Properties

The default configuration file for Spring Boot applications is application.properties. This is where you can configure various aspects of your microservice.

For example, let’s configure the port number to run on:

propertiesCopyEditserver.port=8080

Step 2: Configure Eureka Client (if using Service Discovery)

If you want this microservice to be registered with Eureka, you will need to add the necessary configuration. First, add the Eureka client dependency in your pom.xml:

xmlCopyEdit<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

Next, configure Eureka in your application.properties:

propertiesCopyEditspring.application.name=microservice-demo
eureka.client.service-url.defaultZone=http://localhost:8761/eureka

This configuration tells the service to register itself with a Eureka server running on localhost:8761. We will set up the Eureka server in a subsequent module.


6. Communicating Between Microservices

Step 1: Creating Another Microservice

Let’s create a second microservice that will call the first one. You can follow the same steps to create another Spring Boot application. For this example, we’ll call the second microservice microservice-consumer.

The HelloController for the consumer application will look like this:

javaCopyEditpackage com.example.microserviceconsumer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class HelloController {

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/consume")
    public String consumeService() {
        String serviceUrl = "http://microservice-demo/hello"; // URL of the first microservice
        return restTemplate.getForObject(serviceUrl, String.class);
    }
}

Step 2: Configure RestTemplate Bean

In your microservice-consumer application class, add the RestTemplate bean so that it can be injected into your controller:

javaCopyEditpackage com.example.microserviceconsumer;

import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class AppConfig {

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder.build();
    }
}

Step 3: Running Both Microservices

Now, run both microservices:

  1. Run the microservice-demo application.
  2. Run the microservice-consumer application.

When you access:

bashCopyEdithttp://localhost:8081/consume

You should see the message:

csharpCopyEditHello from Spring Boot Microservice!

This confirms that the consumer microservice is successfully calling the provider microservice.


7. Basic Service Discovery with Eureka

In a real-world microservices architecture, you will need to register your microservices with a service registry like Eureka. This allows microservices to discover each other dynamically, without hardcoding hostnames and IP addresses.

We will cover the detailed setup of Eureka in the next module, but for now, ensure that you have added the necessary Eureka dependencies and configurations to both the microservice-demo and microservice-consumer applications.


8. Conclusion

In this module, we have covered the basic setup of building a microservice using Spring Boot. Key topics included:

  • Setting up a Spring Boot project for microservices
  • Creating a simple RESTful endpoint with @RestController
  • Running and testing the microservice
  • Configuring application properties
  • Communicating between two microservices using RestTemplate
  • Introduction to service discovery with Eureka (to be explored in detail in the next module)

Microservices can be complex, but Spring Boot provides the tools to help you quickly create scalable, maintainable, and cloud-ready applications.