[JAVA] Spring Boot Introductory Guide I tried [Consuming a RESTful Web Service]

Purpose

For those who have finished working on 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 Consuming 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 a review of the Quickstart Guide Click here for a review of Building a RESTful Web Service

1. Start the Spring Boot project!

First, access spring initializr.

  1. Click the ADD DEPENDENCIES button and add Spring Web. 2.Artifact, Name changed to consuming rest.
  2. Change Java to 11.

Then click the GENERATE button to download the Zip file.

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

Extract the downloaded Zip file and you're ready to go.

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 Quote.java!

Create a Quote.java file in src / main / java / com / example / consumingrest /.

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

Add the code in the Quote.java file.

Quote.java


package com.example.consumingrest;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown = true)
public class Quote {

  private String type;
  private Value value;

  public Quote() {
  }

  public String getType() {
    return type;
  }
  public void setType(String type) {
    this.type = type;
  }

  public Value getValue() {
    return value;
  }
  public void setValue(Value value) {
    this.value = value;
  }

  @Override
  public String toString() {
    return "Quote{" +
        "type='" + type + '\'' +
        ", value=" + value +
        '}';
  }
}

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

@JsonIgnoreProperties

When converting a Java object to JSON, or when receiving a JSON string and converting it to a Java object It is an annotation that excludes multiple fields from conversion.

By setting ʻignoreUnknown = true`, you can prevent an exception when trying to convert an undefined (extra) property, and only convert type and value.

② Declaration of variables

python


private String type;
private Value value;

Declares a string type type and a Value type value variable.

The access modifier is private, so you can only access it from within the same class **.

③ Constructor, getter / setter method definition

python


//constructor
public Quote() {
}

//type getter/Setter method
public String getType() {
  return type;
}
public void setType(String type) {
  this.type = type;
}

//value getter/Setter method
public Value getValue() {
  return value;
}
public void setValue(Value value) {
  this.value = value;
}

It defines a constructor with no arguments.

It defines a getter method to get the value of type and value, and a setter method to set the value.

@Override

python


@Override
public String toString() {
  return "Quote{" +
      "type='" + type + '\'' +
      ", value=" + value +
      '}';
}

The toString method is a method that returns a string representation as defined in the java.lang.Object class. The @Override annotation overrides the toString method defined in the ʻObject class with this class. It is an annotation to specify `.

If it is not overridden correctly, an error will occur. Therefore, if you make a typo like toStrign (), an error will occur at compile time and it will tell you.

This time, I'm overriding it to return a string to display the type and value for clarity.

Quote.java is now complete.

Let's create Value.java!

Create a Value.java file in src / main / java / com / example / consumingrest /.

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

Add code in the Value.java file.

Value.java


package com.example.consumingrest;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown = true)
public class Value {

  private Long id;
  private String quote;

  public Value() {
  }

  public Long getId() {
    return this.id;
  }
  public String getQuote() {
    return this.quote;
  }

  public void setId(Long id) {
    this.id = id;
  }
  public void setQuote(String quote) {
    this.quote = quote;
  }

  @Override
  public String toString() {
    return "Value{" +
        "id=" + id +
        ", quote='" + quote + '\'' +
        '}';
  }
}

Value.java is almost the same as Quote.java.

Let's edit ConsumingrestApplication.java!

I think the default state is as follows.

ConsumingrestApplication.java


package com.example.consumingrest;

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

@SpringBootApplication
public class ConsumingrestApplication {

  public static void main(String[] args) {
    SpringApplication.run(ConsumingrestApplication.class, args);
  }

}

Add the code while referring to the formula.

ConsumingrestApplication.java


package com.example.consumingrest;

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

//Added code
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
public class ConsumingrestApplication {

  //Added code
  private static final Logger log = LoggerFactory.getLogger(ConsumingrestApplication.class);

  public static void main(String[] args) {
    SpringApplication.run(ConsumingrestApplication.class, args);
  }

  //Added code
  @Bean
  public RestTemplate restTemplate(RestTemplateBuilder builder) {
    return builder.build();
  }

  //Added code
  @Bean 
  public CommandLineRunner run(RestTemplate restTemplate) throws Exception {
    return args -> {
      Quote quote = restTemplate.getForObject(
        "https://gturnquist-quoters.cfapps.io/api/random", Quote.class);
      log.info(quote.toString());
  }

}

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

① log for log output

python


private static final Logger log = LoggerFactory.getLogger(ConsumingrestApplication.class);

Logger and LoggerFactory are used to display the log in the terminal. You can get the log by specifying the class in the argument of LoggerFactory.getLogger ().

②RestTemplate

python


//Added code
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
  return builder.build();
}

RestTemplate is an HTTP client class that provides methods for calling REST APIs (Web APIs). This time, we will send a GET request to the URL and use it to store the content of the destination response in Quote.class.

It is registered in the DI container using the annotation @Bean and RestTemplateBuilder. Bean registration is an annotation that allows you to set various Spring settings in Java code. You must add @Configuration, but it is included in the annotation @SpringBootApplication.

③CommandLineRunner

python


//Added code
@Bean 
public CommandLineRunner run(RestTemplate restTemplate) throws Exception {
  return args -> {
    Quote quote = restTemplate.getForObject(
      "https://gturnquist-quoters.cfapps.io/api/random", Quote.class);
    log.info(quote.toString());
}

CommandLineRunner is a functional interface with a method called run. Therefore, here, the run method is overridden.

Spring Boot will call it after running the app.

As a processing flow, The result of restTemplate.getForObject () is assigned to the quote variable of type Quote. The URL to send the GET request is specified in the first argument, and the class to store the content of the response of the destination is specified in the second argument.

After that, the info method of log defined in ① is called, and the toString method of Quote class is called in it.

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 a while, the following characters will appear in the terminal.

Terminal


Quote{type='success', value=Value{id=12, quote='@springboot with @springframework is pure productivity! Who said in #java one has to write double the code than in other langs? #newFavLib'}}

This id and quote are written randomly, so if you stop the application and enter the execute command again in the terminal.

Terminal


Quote{type='success', value=Value{id=4, quote='Previous to Spring Boot, I remember XML hell, confusing set up, and many hours of frustration.'}}

It has a different id and quote than before.

Reference site

RestTemplate CommandLineRunner ** Ignore unknown properties when deserializing with jackson ** ** Understanding DI ** ** Get a feel for how Spring DI container works ** ** Create a simple command line application with Spring Boot **

Recommended Posts

Spring Boot Introductory Guide I tried [Consuming a RESTful Web Service]
I tried Spring Boot introductory guide [Building 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
A trip to decipher Spring's "GUIDES" Consuming a RESTful Web Service Edition.
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 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)
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
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
A memo that touched Spring Boot
I tried printing a form with Spring MVC and JasperReports 2/3 (form template creation)
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)
I introduced OpenAPI (Swagger) to Spring Boot (gradle) and tried various settings