I tried Spring Boot introductory guide [Building a RESTful Web Service]

Purpose

For those who have completed the Spring Quickstart Guide, those who have started learning Spring Boot, and those who want to review it.

The official is a popular guide, so give it a try! I will share what I learned by actually working on Building a RESTful Web Service.

Development environment


OS: macOS Mojave version 10.14.6
Text editor: Visual Studio Code (hereinafter VSCode)
Java: 11.0.2

Click here for the previous review

1. Start the Spring Boot project!

First, access spring initializr.

Click the ** ADD DEPENDENCIES ** button. スクリーンショット_2020-06-29_13_14_12.png

Type web and select Spring Web.

スクリーンショット 2020-06-29 13.30.24.png

Artifact, Name changed to ** restservice **. The Java version is 11, so select 11.

スクリーンショット_2020-07-01_14_56_49.png

Click the GENERATE button.

The Zip file will be downloaded, so

スクリーンショット 2020-07-01 15.09.25.png

Extract the Zip file.

スクリーンショット 2020-07-01 15.10.29.png

I'm ready.

2. Add code!

Open the previous folder with VS Code. We recommend installing the Java Extension Pack for extensions. It is said that you should install it.

スクリーンショット 2020-06-30 10.08.25.png

Let's create Greeting.java!

Create a Greeting.java file in src / main / java / com / example / restservice /.

スクリーンショット 2020-07-01 15.30.40.png

Add the code in the Greeting.java file.

Greeting.java completed form


package com.example.restservice;

public class Greeting {
  private final long id;
  private final String content;

  public Greeting(long id, String content) {
    this.id = id;
    this.content = content;
  }

  public long getId() {
    return id;
  }
  public String getContent() {
    return content;
  }
}

We will dig deeper into the code we added to the Greeting.java file.

① Declaration of constant

python


private final long id;
private final String content;

The constants of long type id and string type content are declared respectively.

Since the access modifier is private and the final modifier is used, it is a constant ** that can only be accessed from within the same class. Since it is a constant, it is not possible to reassign the value.

② Constructor definition

public Greeting(long id, String content) {
  this.id = id;
  this.content = content;
}

Describe the process you want to perform at the same time when instantiated. This time, the initial values are assigned to the instance constants id and content.

③ Definition of getter method

python


public long getId() {
  return id;
}
public String getContent() {
  return content;
}

It is a method to call the value of id and content.

Greeting.java is now complete!

Let's create GreetingController.java!

Create a GreetingController.java file in src / main / java / com / example / restservice /.

スクリーンショット 2020-07-01 16.36.36.png

Add the code in the GreetingController.java file.

GreetingController.java completed form


package com.example.restservice;

import java.util.concurrent.atomic.AtomicLong;

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

@RestController
public class GreetingController {
  private static final String template = "Hello, %s!";
  private final AtomicLong counter = new AtomicLong();

  @GetMapping("/greeting")
  public Greeting greeting(@RequestParam(value = "name", defaultValue = "World") String name) {
    return new Greeting(counter.incrementAndGet(), String.format(template, name));
  }
}

We will dig deeper into the code we added to the GreetingController.java file.

①@RestController

python


@RestController
public class GreetingController {
}

By writing this annotation, Spring Boot will recognize it as a Controller. The return value of the method becomes the content of the response as it is without transitioning to View.

The greeting method described later uses the Greeting object as the return value, but since Spring Boot automatically converts it to JSON, JSON will be displayed on the screen.

② Declaration of constant

python


private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();

The constants of string type template and long type counter are declared respectively.

Since the access modifier is private and the final modifier is used, it is a constant ** that can only be accessed from within the same class. Since it is a constant, it is not possible to reassign the value.

** template ** uses the static modifier, so it is a constant that exists only once for the class. And % s is described because when using the method called String.format, the format decided as the first argument must be specified.

** counter ** uses the AtomicLong class. I will explain why this class is used later.

③ Definition of greeting method

python


@GetMapping("/greeting")
public Greeting greeting(@RequestParam(value = "name", defaultValue = "World") String name) {
  return new Greeting(counter.incrementAndGet(), String.format(template, name));
}

@GetMapping ("/ greeting ") is an annotation for processing the greeting method when the URL is accessed as 〇〇 / greeting (when there is a GET request). It means that the greeting method is called when http: // localhost8080 / greeting is accessed.

The argument @RequestParam of the greeting method can receive the query parameter of the URL. Specifies what value is stored in ** String name **,

If http: // localhost8080 / greeting is accessed, World is stored in name, If http: // localhost8080 / greeting? name = tanaka is accessed, name will contain tanaka.

Finally, dig deep into the return part.

python


return new Greeting(counter.incrementAndGet(), String.format(template, name));

Every time http: // localhost8080 / greeting is accessed, it returns a Java object that instantiates the Greeting class. We are passing counter.incrementAndGet () as the first argument of the new Greeting constructor and String.format (template, name) as the second argument.

Instantiation of Greeting class, increment of counter, return of character string by specifying format, and multiple processing are performed at the same time.

Increment can be described as counter ++;, but it may not be processed correctly when multiple processes are executed.

We define a counter in the AtomicLong class above and use the class's method ʻincrementAndGet ()` to increment the current value (counter) and return the incremented value.

Atomic is said to be an atomic operation, and I interpreted it as defining a counter using the AtomicLong class in order not to interrupt other processing until the addition is completed.

3. Let's run it!

Now that the application is ready to run, let's check.

Enter the following command in the terminal and press Enter.

Terminal


$ ./mvnw spring-boot:run

After waiting for about 2 seconds, when you access http: // localhost: 8080 / greeting,

スクリーンショット 2020-07-02 11.33.39.png

Next, when you access with http: // localhost: 8080 / greeting? Name = tanaka,

スクリーンショット 2020-07-02 11.35.10.png

Next, when you access with http: // localhost: 8080 / greeting? Name = suzuki,

スクリーンショット 2020-07-02 11.35.31.png

The id increases each time you access, and when you access with / greeting? Name = arbitrary character string, the entered value is displayed!

Reference site

** Spring Boot Getting Started Guide ** ** Oracle's AtomicLong ** ** What does it mean to be atomic ** ** Multithreading ** ** [Basics of Java Concurrency](https://qiita.com/stk_odoroki/items/bddaeec8775406c63258#%E3%82%A2%E3%83%88%E3%83%9F%E3%83%83%E3 % 82% AF% E6% 80% A7) **

Recommended Posts

I tried Spring Boot introductory guide [Building a RESTful Web Service]
Spring Boot Introductory Guide I tried [Consuming a RESTful Web Service]
Spring Boot Introductory Guide I tried [Accessing Data with JPA]
I tried to clone a web application full of bugs with Spring Boot
I tried GraphQL with Spring Boot
I tried Flyway with Spring Boot
I tried Lazy Initialization with Spring Boot 2.2.0
Java beginner tried to make a simple web application using Spring Boot
I tried Spring.
Create a web api server with spring boot
[I tried] Spring tutorial
05. I tried to stub the source of Spring Boot
I tried to reduce the capacity of Spring Boot
I tried Spring Batch
I made a Restful server and client in Spring.
A memorandum when creating a REST service with Spring Boot
I wrote a test with Spring Boot + JUnit 5 now
I tried to implement a buggy web application in Kotlin
I haven't understood after touching Spring Boot for a month
Introducing Spring Boot2, a Java framework for web development (for beginners)
I tried to get started with Swagger using Spring Boot
I made a simple MVC sample system using Spring Boot
[Spring Boot] Web application creation
I tried Spring State machine
Implement a simple Web REST API server with Spring Boot + MySQL
I tried printing a form with Spring MVC and JasperReports 1/3 (JasperReports settings)
Let's make a book management web application with Spring Boot part1
I tried printing a form with Spring MVC and JasperReports 3/3 (Spring MVC control)
Let's make a book management web application with Spring Boot part3
A trip to decipher Spring's "GUIDES" Consuming a RESTful Web Service Edition.
I tried to create a Spring MVC development environment on Mac
Let's make a book management web application with Spring Boot part2
I made a simple search form with Spring Boot + GitHub Search API.
I tried using Spring + Mybatis + DbUnit
I tried a little digdag docker.run_options
Spring Boot: Restful API sample project
spring boot access authorization RESTful API
A memo that touched Spring Boot
I tried printing a form with Spring MVC and JasperReports 2/3 (form template creation)
I tried to make a Web API that connects to DB with Quarkus
Automatically deploy a web application developed in Java using Jenkins [Spring Boot application]
Gorigori SIer SE tried to create a Web service by personal development
[Spring Boot] I stumbled upon a method call count test (Spock framework)
[LINE BOT] I made a ramen BOT with Java (Maven) + Heroku + Spring Boot (1)