In this article we will see how to create microservices using Spring Boot and Rest APIs. We will create an example microservice using spring Boot, while this service will interact with other micro services and outer world with the help of REST APIs.

What is a Microservice architecture ?

A Microservice architecture involves multiple independently deployable services (Microservices) capable of working independently as well as together in a connected big project.

Microservice architecture is essentially a way to architect a large piece of software by producing a series of smaller applications that can all work together if needed along with working perfectly fine all by themselves.

What is REST ?

REST (Representational State Transfer), is a method of exposing data that provides standards between apps and systems, making it easier for systems to interact with each other.

Microservices can be implemented in many ways, REST over HTTP is the most popular way to implement Microservices. REST APIs makes it possible to expose these microservices while keeping them decoupled.

How to develop a microservice in Spring Boot

In this section we will discuss, how to create a microservice from scratches using Spring Boot, a step by step implementation guide is provides below:

1) Create Java project with Maven


$ mvn archetype:generate -DgroupId=com.tb.java -DartifactId=ApiServer -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

2) Convert to eclipse


$ cd ApiServer/
$ mvn eclipse:eclipse

3) Import project in Eclipse

Import newly created Java project in Eclipse, you will find a pom.xml file, replace this with the content written below:
<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 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.tb.java</groupId>
	<artifactId>ApiServer</artifactId>
	<packaging>jar</packaging>
	<version>1.0-SNAPSHOT</version>
	<name>ApiServer</name>
	<url>http://maven.apache.org</url>
	<properties>
		<java.version>1.8</java.version>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.0.RELEASE</version>
	</parent>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

	<repositories>
		<repository>
			<id>repository.spring.release</id>
			<name>Spring GA Repository</name>
			<url>http://repo.spring.io/release</url>
		</repository>
	</repositories>
</project>

4) Create a spring boot application launch class

/ApiServer/src/main/java/com/tb/java/App.java
package com.tb.java;

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

@ComponentScan({ "com.tb.models", "com.tb.services" })
@SpringBootApplication
public class App {
	public static void main(String[] args) {
		ApplicationContext context = SpringApplication.run(App.class, args);
	}
}
In this class we have instantiated ApplicationContext, this will load all the Spring beans as per the configuration. We have also passed command line arguments to it, that will convert them to spring properties. Read More about Spring Boot

5) Exposing Microservice in REST

So far we have Just created and configured a Spring Boot application, from now on we will create a Controller that will expose the microservice in REST format.

Let us assume, this particular service is responsible for providing details of Student resource, we will now create REST based URLs to interact with the service regarding Student resource.

/src/main/java/com/tb/models/Student.java

package com.tb.models;

public class Student {
	private int id;
	private String name;
	private int 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 int getAge() {
		return age;
	}

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

}

/src/main/java/com/tb/services/StudentResource.java

package com.tb.services;

import java.util.List;
import java.util.ArrayList;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.tb.models.Student;

@RestController
@RequestMapping("/student")
public class StudentResource {

	// Adding resource
	@RequestMapping(value = "/", method = RequestMethod.POST)
	public String add(@RequestBody Student student) {

		// Actual code to add an student in DB or other format goes here !
		return "Student added successfully";

	}

	// Update resource
	@RequestMapping(value = "/", method = RequestMethod.PUT)
	public String update(@RequestBody Student student) {

		// Actual code to update an student in DB or other format goes here !
		return "Student updated successfully";

	}

	// Getting a single resource based on id
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	public Student get(@PathVariable Integer id) {

		// Actual code to get student based on id from source
		return new Student(id, "Andrew", 23);

	}

	// Getting all resource
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public List<Student> getAll() {

		// Actual code to get all students from source
		List<Student> list = new ArrayList<>();
		list.add(new Student(1, "Andrew", 23));
		return list;

	}

	// Deleting a single resource based on id
	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	public String delete(@PathVariable Integer id) {

		// Actual code to delete student based on id from source
		return "Student deleted successfully";

	}

	// Deleting all resource
	@RequestMapping(value = "/", method = RequestMethod.DELETE)
	public String deleteAll() {

		// Actual code to delete all students from source

		return "All student deleted successfully";

	}

}

6) Run a spring boot (Maven) application

In order to run a boot application, following command can be used from the project home directory:

$ mvn spring-boot:run
This will print logs something like this, an embedded Tomcat will be started on Port 8080, with the application deployed on it.

[INFO] Scanning for projects...
[INFO]                                                                         
[INFO] ------------------------------------------------------------------------
[INFO] Building ApiServer 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] 
[INFO] >>> spring-boot-maven-plugin:2.0.4.RELEASE:run (default-cli) > test-compile @ ApiServer >>>

...
...
...


[INFO] --- spring-boot-maven-plugin:2.0.4.RELEASE:run (default-cli) @ ApiServer ---

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.0.4.RELEASE)

....
....
....

2018-09-12 14:55:14.723  INFO 18861 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2018-09-12 14:55:14.728  INFO 18861 --- [           main] com.tb.java.App                          : Started App in 2.824 seconds (JVM running for 6.412)

7) Testing Microservice

1) Adding a Resource(Student)

URL: http://localhost:8080/student/
Method: POST
Content-Type: application/json
Body:
{  
   "id":1,
   "name":"Andrew",
   "age":27
}


Response: Student added successfully

2) Update a Resource(Student)

URL: http://localhost:8080/student/
Method: PUT
Content-Type: application/json
Body:
 {  
   "name":"Andrew Adams",
}

Response: Student updated successfully

3) Getting resource based on ID

URL: http://localhost:8080/student/1
Method: GET
Response:
{
    "id": 1,
    "name": "Andrew",
    "age": 23
}


4) Delete resource based on ID

URL: http://localhost:8080/student/1
Method: DELETE
Response: Student deleted successfully

5) Delete all resources based on ID

URL: http://localhost:8080/student/
Method: DELETE
Response: All student deleted successfully
  • By Techburps.com
  • Sep 12, 2018
  • Spring Framework