Getting Started · Building an Application with Spring Boot

This is a guide to create a simple RESTful web service with Spring-boot. Here we will build a service that will accept HTTP GET requests and sends a JSON response. We are going to create a Student master list and expose a REST api to search in the list of students. 

Use the Students REST API :

To interact with the Students REST API, you send HTTP GET requests.

https://localhost:8080/students?studentId=120

And if the application founds the student in it's master list , then respond back with the student as an JSON object:

{
  "Student": {
    "studentId": "120",
    "name": "Ninja Panda",
    "rollNo": "CS-120",
    "department": "Computer Science",
    "shortCode": "CS",
    "year": "2nd"
  }
}

What you’ll need to create the spring-boot application :

1. A favorite text editor or IDE, we are using Eclipse.
2. JDK 1.8 or later
3. Maven 3.0+

Steps to Create our spring-boot application :

1.  In Eclipse navigate through File →  New →  Other.. | OR press (Ctrl + N).

2.  Then search for maven and Select Maven Project and click on Next.

3.  Now choose a location for the project and click on Next.
 

4.  Now Select an Archetype and click on Next.
   

5.  Enter Group Id and Artifact Id and click on Finish. After this step our project is created.
  

6.  Open you pom.xml and replace the content with the following.

<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.tuturself</groupId>
	<artifactId>spring.boot</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.1.RELEASE</version>
	</parent>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>com.jayway.jsonpath</groupId>
			<artifactId>json-path</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<properties>
		<java.version>1.8</java.version>
	</properties>


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

	<repositories>
		<repository>
			<id>spring-releases</id>
			<url>https://repo.spring.io/libs-release</url>
		</repository>
	</repositories>
	<pluginRepositories>
		<pluginRepository>
			<id>spring-releases</id>
			<url>https://repo.spring.io/libs-release</url>
		</pluginRepository>
	</pluginRepositories>
</project>

7.  Now go to project directory and execute the following command to build it.

mvn clean install -DskipTests=true


    
8. In this state you should be able to build your application.

Writing the code :
To finish our application we need to create 2 Java files. Maven will compile sources from src/main/java by default so we need to create our controller class and the Student class in that package.To model the Student representation, you create a resource representation class. Provide a plain old java object with fields, constructors, and accessors for the attributes of Student. Following is our Student representation class.

package com.tuturself.spring.boot;

public class Student {

	private Integer studentId;
	private String name;
	private String rollNo;
	private String department;
	private String shortCode;
	private String year;
	
	public Student(Integer studentId, String name, String rollNo, 
		String department, String shortCode, String year) {
		super();
		this.studentId = studentId;
		this.name = name;
		this.rollNo = rollNo;
		this.department = department;
		this.shortCode = shortCode;
		this.year = year;
	}

	public Integer getStudentId() {
		return studentId;
	}

	public void setStudentId(Integer studentId) {
		this.studentId = studentId;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getRollNo() {
		return rollNo;
	}

	public void setRollNo(String rollNo) {
		this.rollNo = rollNo;
	}

	public String getDepartment() {
		return department;
	}

	public void setDepartment(String department) {
		this.department = department;
	}

	public String getShortCode() {
		return shortCode;
	}

	public void setShortCode(String shortCode) {
		this.shortCode = shortCode;
	}

	public String getYear() {
		return year;
	}

	public void setYear(String year) {
		this.year = year;
	}
}

Create a Resource Controller:
In Spring’s approach to building RESTful web services, HTTP requests are handled by a controller. These components are easily identified by the @RestController annotation, and the StudentAPI Controller below handles GET requests for /students by returning a Student Object:

package com.tuturself.spring.boot;

import java.lang.reflect.Array;
import java.util.HashMap;
import java.util.Map;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@EnableAutoConfiguration
public class StudentAPI {

  private static Map<Integer, Student> studentDB;

  @RequestMapping("/students")
  public Student searchStudent(
		@RequestParam(name = "studentId", required = true) Integer studentId) {
	return studentDB.get(studentId);
  }

  public static void main(String[] args) throws Exception {
	createStudentList();
	SpringApplication.run(StudentAPI.class, args);
  }

  private static void createStudentList() {
	studentDB = new HashMap<>();
	for (int i = 0; i < 100; i++) {
		Student student = new Student(i, "Name-" + i, "CS-" + i, "Computer Science", "CS", "2nd");
		studentDB.put(student.getStudentId(), student);
	}
  }  
}

Understanding the annotations: The first annotation on our StudentAPI class is @RestController. This is known as a stereotype annotation. It provides hints for people reading the code, and for Spring, that the class plays a specific role. In this case, our class is a web @Controller so Spring will consider it when handling incoming web requests.

Difference between @Controller and @RestController : A key difference between a traditional MVC controller and the RESTful web service controller above is the way that the HTTP response body is created. Rather than relying on a view technology to perform server-side rendering of the student data to HTML, this RESTful web service controller simply populates and returns a Student object. The object data will be written directly to the HTTP response as JSON.

This code uses Spring 4’s new @RestController annotation, which marks the class as a controller where every method returns a domain object instead of a view. It’s shorthand for @Controller and @ResponseBody rolled together.

@RequestMapping annotation : The @RequestMapping annotation provides “routing” information. It is telling Spring that any HTTP request with the path “/students” should be mapped to the searchStudent() method.

@EnableAutoConfiguration annotation : The second class-level annotation is @EnableAutoConfiguration. This annotation tells Spring Boot to “guess” how you will want to configure Spring, based on the jar dependencies that you have added. Since spring-boot-starter-web added Tomcat and Spring MVC, the auto-configuration will assume that you are developing a web application and setup Spring accordingly.

@RequestParam annotation : @RequestParam binds the value of the query string parameter studentId into the studentId parameter of the searchStudent() method. This query string parameter is explicitly marked as required (also required=true by default): if it is absent in the request, then the request will fail.

The implementation of the method body searches for the Student in our dummy Student database and returns the object. The Student object must be converted to JSON. Thanks to Spring’s HTTP message converter support, you don’t need to do this conversion manually. Because Jackson 2 is on the classpath, Spring’s MappingJackson2HttpMessageConverter is automatically chosen to convert the Greeting instance to JSON.

Running the example: At this point our application should work. Since we have used the spring-boot-starter-parent POM we have a useful run goal that we can use to start the application. Type mvn spring-boot:run from the root project directory to start the application/ or you can build the application and run the main method in Eclipse: It will print like following in console.

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

If you open a web browser to http://localhost:8080/students?studentId=18 you should see the following output:

{"studentId":18,"name":"Name-18","rollNo":"CS-18","department":"Computer Science","shortCode":"CS","year":"2nd"}

 

spring 12

FOLLOW US ON LinkedIn



Explore Tutu'rself