Getting Started with SpringBoot: Scaffolding & Annotations (Part2)

Ragunath Rajasekaran
7 min readJul 21, 2019

--

This is a beginner level tutorial where we are going to learn how quickly we can span web services using Spring Framework. This tutorial series would cover how to write web services for expense manager application using SPRING BOOT. This is the Part 2 of my tutorial series. Get the glimpse of what we are trying to achieve as a whole, please checkout part1.

What are we going to develop?

We are going to create a new Spring project to perform CRUD operations for Account on Database through web services. We will develop the following endpoints and will interact with Database to manipulate Accounts,

  • /accounts endpoint to create an Account in DB through HTTP POST method
  • /accounts endpoint to retrieve All Accounts from DB through HTTP GET method
  • /accounts/{account-id} endpoint to retrieve an Account for an AccountID from DB through HTTP GET method
  • /accounts/{account-id} endpoint to update an Account for an AccountID into DB through HTTP PUT method
  • /accounts/{account-id} endpoint to delete an Account for an AccountID from DB through HTTP DELETE method

In a Nutshell, we do

Interact with HTTP protocol using its methods through Web server

Interact with Database through Spring/Java/JPA

What are we going to cover in this article?

In order to integrate the Account CRUD operation, we have segregated our implementation with multiple different articles. In this article, we scaffold and explain Annotations & DB interactions will be covered in later articles.

Let’s install necessary tools.

Installation

SDKMan is a sophisticated tool to manage Java, Gradle and other tools. It is worth trying.

Scaffolding using Spring.io

Spring.io is one of the easy option to generate Spring project with necessary configuration by using user friendly UI.

Let’s open https://start.spring.io/ web page to bootstrap Spring project.

Then give following details to generate Spring Application,

  • Artifact coordinates > Group : com.rrr.expense.manager
  • Artifact coordinates > Artifact : em-api
  • Include dependencies : Spring Web Starter
  • Choose Gradle
  • Choose Java
  • Spring Boot 2.1.6 ( At the time of writing 2.1.6 is the latest one )

Click Generate the project and project will be downloaded.

Plenty of IDEs are available for developing Java applications. Please use which one is comfortable for you. I am going to use IntelliJ IDE

Let us import the project.

Let us run the application

Application starts running without any error. See what spring offers us to span application up & running

  • Profiles are used to configure application for different environments like DEV, QA, UAT & PROD. We haven’t configured anything the sort now. So Spring fall back to default
  • Tomcat starts on port 8080. It is a default one configured on Spring.
  • WebApplication context initialised and application started

There are a lot happening when Spring starts. But with proper abstraction, Spring hides the complexity from end developer.

Project Architecture

Controller

  • Responsible to respond for client HTTP requests
  • Controller delegates request processing to service layer and get back response from it and hand it to server.

Service

  • Contains business logic
  • Interact with other dependent services

Repositories

  • Interacts with Datasource (Ex Database, File System, etc) and knows about it
  • Service layer propagate request to this layer.

RestController Annotation

RestController annotation is an interface in Spring to configure Java interface, class or enum to receive http client request. If we see definition of it, we can see that it is being configured with other annotations.

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController
  • Target annotation Indicates the contexts in which an annotation type is applicable. It makes the RestController annotation to be used on a specific context. If we further dig deep then we can find that element context can be configured through ElementType enum and also can identify different type of Java Elements a Target could be operated with.
public enum ElementType {
/** Class, interface (including annotation type), or enum declaration */
TYPE
,
/** Field declaration (includes enum constants) */
FIELD
,
/** Method declaration */
METHOD
,
/** Formal parameter declaration */
PARAMETER
,
/** Constructor declaration */
CONSTRUCTOR
,
/** Local variable declaration */
LOCAL_VARIABLE
,
/** Annotation type declaration */
ANNOTATION_TYPE
,
/** Package declaration */
PACKAGE
,
/**
* Type parameter declaration
*
*
@since 1.8
*/
TYPE_PARAMETER
,
/**
* Use of a type
*
*
@since 1.8
*/
TYPE_USE
,
/**
* Module declaration.
*
*
@since 9
*/
MODULE
}

Here RestController marked as an ElementType.Type, means, it can be applied to class, interface and enum level.

  • Retention annotation indicates how long annotations with the annotated type are to be retained. It restricts the RestController for how long it can keep engaged in Spring. If we further dig deep then we can find that Retention can be configured through RetentionPolicy enum. It provides different type of policies to keep hold of Java elements.
public enum RetentionPolicy {
/**
* Annotations are to be discarded by the compiler.
*/
SOURCE
,
/**
* Annotations are to be recorded in the class file by the compiler
* but need not be retained by the VM at run time. This is the default
* behavior.
*/
CLASS
,
/**
* Annotations are to be recorded in the class file by the compiler and
* retained by the VM at run time, so they may be read reflectively.
*
*
@see java.lang.reflect.AnnotatedElement
*/
RUNTIME
}

Here RestController marked as an RetentionPolicy.RUNTIME, means, it is being recorded on Compile time and VM will make use of Reflection API to keep hold at runtime in VM.

Likewise, we can analyse each annotations. But what we need to understand. Annotation is an interface and a java code to configure Java elements(Class, interface, enum, methods, method params, & etc) in a way Spring convention expects. For example,

- If we want a class to receive HTTP request then we have to mark it with annotation (RestController).

- If we want a method to response for HTTP GET request then we have to mark it either with RequestMapping or GetMapping annotation

Annotation can be applicable to Java class, interface, enum, method, compile time, runtime & etc. Annotations travel along with us through out our journey to configure Java class in a way Spring/we want. We can even configure Java classes through XML, but we are going to use Annotation.

Spring RestController

Let’s create new package controllers and create a class called HealthRestController.

Open HealthRestController class and annotate as RestController,

Create new method health which will return Service is Up & Running Time Stamp. By adding @GetMapping annotation configures the health method to be executed whenever user calls the root endpoint.

package com.rrr.expense.manager.emapi.controllers;import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.Instant;@RestController
public class HealthRestController {
@GetMapping(value = "/health")
public String health() {
return "Service is Up & Running. " + Instant.now().toString();
}
}

It is time to build & run. I am using Postman to validate REST APIs.

What we did so far,

  • Created a new Spring project using spring.io
  • Imported Spring into IntelliJ IDE and ran it
  • Created a HealthRestController and configured /health endpoint.

lets analyse /health endpoint request & response in detail. So let’s open PostMan Console from PostMan to analyse it.

We have returned only Service is Up & Running. 2019–06–30T07:38:10.016557Z but it shows lot of information. Let’s list results of what we are seeing on our analysis,

  • HTTP Request Endpoint We configured /health endpoint in Java code using GetMapping annotation
  • HTTP Request Headers Postman added these headers to make call
  • HTTP Status Code We haven’t returned this
  • HTTP Response Headers We haven’t returned this
  • HTTP Response Body Yes. We have return this through method health()

If we haven’t return this then who? RestController method’s return type will be a ResponseEntity class. What does that mean? Return value of method will be embedded as ResponseEntity body and Spring also adds HTTP Status Code & HTTP Response Headers. Though we are returning ‘String’ as a type, RestController returns ResponseEntity by embedding ‘String’ as a body.

If so what ResponseEntity is? It represents the entire HTTP response and it contains status code, body & headers. If we have seen the structure of it, it extends HttpEntity class and contains attributes for three entities. It also configured with Builder pattern. We can construct ResponseEntity as typical Java class or use Builder pattern to do so.

What we did so far,

  • What are planning to do in the entire Spring Series (CRUD for Account)
  • What is the scope of this article
  • Scaffolded Spring application using Spring.io
  • Imported project into IntelliJ IDE
  • Run and see the request/response in Postman console
  • Analysed about Spring Annotations and we understood that it can be applied to different Java elements.
  • Analysed about RestEntity and its architecture.

We will write endpoints to perform CRUD for Account in next article.

Please checkout the continuation of this tutorial.

--

--

Ragunath Rajasekaran

Sr. Tech Lead | Spring Boot | Big Data | AWS | Terraform | Spark | React | Docker