This guide walks you through the process of creating a "Hello World"RESTful web service with Spring.
You will build a service that will accept HTTP GET requests at
http://localhost:8080/greeting
or http://localhost:8080/greeting?name=#
.
And it will respond with a JSON representation of a greeting.
我还引入了 lombok 依赖。
src/main/java/com/example/restservice/Greeting.java
package com.example.restservice;
import lombok.Data;
@Data
public class Greeting {
private final long id;
private final String content;
public Greeting(long id, String content) {
this.id = id;
this.content = content;
}
}
此应用程序使用使用 Jackson JSON 库自动地将类型Greeting的实例封装成JSON,网络启动器默认包含Jackson。
In Spring’s approach to building RESTful web service, HTTP requests are handled by a controller.
src/main/java/com/example/restservice/GreetingController.java
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));
}
}
(1)
@GetMapping
注释可以确保 HTTP GET 请求到的 /greeting 被映射到 greeting() 方法。
(2)@RequestParam
将查询字符串参数name的值绑定到greeting()方法中的参数name。如果请求中不存在参数name,则使用 defaultValue 中的值 “World"。
(3) 线程安全的AtomicXXX
,适合用于多线程环境。.incrementAndGet()自增+1
。
(4)@RestController
使这个类作为一个使所有方法返回域对象而不是视图的一个控制器。它包含 @Controller 和 @ResponseBody
package com.example.restservice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class RestServiceApplication {
public static void main(String[] args) {
SpringApplication.run(RestServiceApplication.class, args);
}
}