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
First, access spring initializr.
Spring Web
.
2.Artifact, Name changed to consuming rest
.Then click the GENERATE
button to download the Zip file.
Extract the downloaded Zip file and you're ready to go.
Open the previous folder with VS Code. We recommend installing the Java Extension Pack for extensions. It is said that you should install it.
Create a Quote.java file in src / main / java / com / example / consumingrest /.
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.
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 **.
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.
Create a Value.java file in src / main / java / com / example / consumingrest /.
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.
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.
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.
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.
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