[Java] Spring Boot Getting Started Guide [Building a RESTful Web Service]

4 minute read

Purpose

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

The official guide is popular, 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 (VSCode)
Java: 11.0.2

Click here for the last review

Let’s start #1.SpringBoot project!

First, access spring initializr.

Click the ADD DEPENDENCIES button. ![Screenshot _2020-06-29_13_14_12.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/555244/2921a113-d5d0-cedf-deeb-83b23326975f.(png)

Enter web and select Spring Web.

![Screenshot 2020-06-29 13.30.24.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/555244/89d906ff-f347-6e4f-8c6d-(737446ab0f30.png)

Artifact, Name has been changed to restservice. Java version is 11, so select 11.

[Screenshot _2020-07-01_14_56_49.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/555244/c29cccba-7ed7-0d79-8fa1-b822fcb29e8a.(png)

Click the GENERATE button.

As the Zip file is downloaded,

![Screenshot 2020-07-01 15.09.25.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/555244/e4ee15f0-1522-a8ea-735c-(3ea2f45851a1.png)

Extract the Zip file.

Screenshot 2020-07-01 15.10.29.png

I’m ready.

2.Let’s add code!

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

![Screenshot 2020-06-30 10.08.25.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/555244/80331ebc-b6e3-af7b-181a-(3c8921288b00.png)

Let’s create ##Greeting.java!

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

![Screenshot 2020-07-01 15.30.40.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/555244/ae74bb20-effd-17c5-c44d-(4346c9fa94fd.png)

Add code inside 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;
  }
}

Let’s dig deeper into the code we added to the Greeting.java file.

① Declaration of constant

``


private final long id;
private final String content;

Declares constants of long type id and string type content.

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

② Constructor definition

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

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

③ Definition of getter method

``


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

This is a method to call the values of id and content.

Greeting.java is now complete!

Let’s create GreetingController.java!

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

Screenshot 2020-07-01 16.36.36.png

Add code inside 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));
  }
}

Let’s dig deeper into the code we added to the GreetingController.java file.

①@RestController

``


@RestController
public class GreetingController {
}

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

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

② Constant declaration

``


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

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 becomes a constant that can only be accessed from within the same class. Since it is a constant, it is impossible to reassign the value.

Since template uses the static modifier, there is only one constant for the class. And %s is described because you have to specify the format determined in the first argument when using the method String.format.

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

③ definition of greeting method

``


@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 `○○/greeting` is accessed in the URL (when there is a GET request).
It means that the greeting method will be called when http://localhost8080/greeting is accessed.

`@RequestParam` of the argument of greeting method can receive the query parameter of URL.
Specify what kind of 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 store tanaka`.

Finally, the return part is deeply dug.


#### **``**
```java

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

Each time http://localhost8080/greeting is accessed, a Java object that instantiates the Greeting class is returned. counter.incrementAndGet() is passed as the first argument of the new Greeting constructor, and String.format(template, name) is passed as the second argument.

It instantiates the Greeting class, increments the counter, returns a character string with a specified format, and performs multiple processes at the same time.

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

The counter is defined in the AtomicLong class above, the method incrementAndGet() of the same class is used, the current value (counter) is incremented, and the incremented value is returned.

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

3.Let’s run!

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

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,

![Screenshot 2020-07-02 11.33.39.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/555244/bd91fa6c-9825-2248-1ac6-(d5b6cefdce67.png)

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

Screenshot 2020-07-02 11.35.10.png

Next, if you access with http://localhost:8080/greeting?name=suzuki,

![Screenshot 2020-07-02 11.35.31.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/555244/cbae67ff-9038-f782-6d9f-(9abb7a751457.png)

Each time you access, the id will increase, 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 Multithread Java Concurrency Basics