[JAVA] A trip to decipher Spring's "GUIDES" Consuming a RESTful Web Service Edition.

Consuming a RESTful Web Service

What is REST?

This article will be helpful.

In Consuming a RESTful Web Service It is a service that allows you to refer to resources (data related to WEB services) by entering a URI in a browser.

This is a convenient mechanism for sharing information with multiple software in a distributed system.

What do you want to do

The spring manual has an API that randomly returns manual text. http://gturnquist-quoters.cfapps.io/api/random This Consuming a RESTful Web Service is a function to get data from this API.

Create a quote class (src / main / java / hello / Quote.java)

src/main/java/hello/Quote.java


package hello;

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 +
                '}';
    }
}

What is @JsonIgnoreProperties?

The following is a quote from the manual.

As you can see, this is a simple Java class with a handful of properties and matching getter methods. It’s annotated with @JsonIgnoreProperties from the Jackson JSON processing library to indicate that any properties not bound in this type should be ignored

@JsonIgnoreProperties is an annotation that ignores a property if it doesn't fit in JSON format. So by adding this, you can ignore unnecessary data. The service connected this time returns data in JSON format, so it seems to be a description corresponding to it. You must have the same properties and names that are returned in JSON.

The contents are simple getters and setters.

toString () method

By default, the toString () method returns a string that represents the reference to the Object, so I'm overriding it. You are trying to return value, which is the sentence quoted as type (described later).

Create a citation content class (src / main / java / hello / Value.java)

src/main/java/hello/Value.java


package hello;

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 + '\'' +
                '}';
    }
}

The contents of the citation are classified into IDs and Quotes into classes. It seems that they are doing it for tidying up. This is used in Quote.java.

Create a class (Application.java) for execution

src/main/java/hello/Application.java


package hello;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.client.RestTemplate;

public class Application {

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

    public static void main(String args[]) {
        RestTemplate restTemplate = new RestTemplate();
        Quote quote = restTemplate.getForObject("http://gturnquist-quoters.cfapps.io/api/random", Quote.class);
        log.info(quote.toString());
    }

}

Output log

private static final Logger log = LoggerFactory.getLogger (Application.class); to get the log, log.info (quote.toString ()); to output. By default, it is output to the console.

Get data from API using RestTemplate

You are getting JSON data by specifying the address with Quote quote = restTemplate.getForObject ("http://gturnquist-quoters.cfapps.io/api/random", Quote.class);.

In getForObject, Quote.class created earlier is set in the second argument. This will create a New Quote class based on the JSON data? It will be stored in the quote variable. Is setValue () of the Quote class also performed automatically at this timing? Value.java is also New and it seems that it is the value of Quote. Perhaps the @JsonIgnoreProperties (ignoreUnknown = true) attached to both classes is automating everywhere, but I couldn't interpret the details. If anyone can understand the behavior behind the scenes, I would appreciate it if you could give me a message.

Use Spring Boot

Since Spring Boot is not used so far, the following is the description method of Application.java when Spring Boot is used. The advantages of using Spring Boot are described as follows.

One of the advantages is that we might want to let Spring Boot manage the message converters in the RestTemplate, so that customizations are easy to add declaratively.

By letting Spring Boot manage message converters in Rest Template, it will be possible to add customization declaratively. It seems that.

Create an execution class for Spring Boot

src/main/java/hello/Application.java


package hello;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
public class Application {

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

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

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

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

The explanation about this code is as follows.

The RestTemplateBuilder is injected by Spring, and if you use it to create a RestTemplate then you will benefit from all the autoconfiguration that happens in Spring Boot with message converters and request factories. We also extract the RestTemplate into a @Bean to make it easier to test (it can be mocked more easily that way).

This is still undecipherable in my learning state. RestTemplateBuilder has This article: Use RestTemplate (HTTP client) with Spring Boot 1.4+ for your reference. In the first place, it is unreasonable that it is suddenly explained to the knowledge premise such as bean even though there is nothing about autodon figuration or bean at this point. Can this manual be systematized? I searched for the part where the explanation of bean is listed, but I can't find the part. Is there no choice but to read it in a book?

Recommended Posts

A trip to decipher Spring's "GUIDES" Consuming a RESTful Web Service Edition.
A trip to decipher Spring's "GUIDES" Scheduling Tasks edition.
Spring Boot Introductory Guide I tried [Consuming a RESTful Web Service]
The road to creating a Web service (Part 1)
I tried Spring Boot introductory guide [Building a RESTful Web Service]
Three Reasons to Frustrate Before the Release of a Web Service
Gorigori SIer SE tried to create a Web service by personal development