Spring Boot 构建一个RESTful Web服务
·
构建RESTful Web服务
本指南将手把手教您如何使用Spring框架创建一个“Hello,World”RESTful网络服务。
1、创建一个数据类Greeting,
package com.example.restservice;
public record Greeting(long id, String content) { }
2、创建一个控制器GreetingController,
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(defaultValue = "World") String name) {
return new Greeting(counter.incrementAndGet(), template.formatted(name));
}
}
3、启动服务类
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);
}
}
4、编译,打包,并启动服务。
java -jar build/libs/gs-rest-service-0.1.0.jar
5、测试运行。
浏览器访问地址 http://localhost:8080/greeting
返回结果如下 {"id":1,"content":"Hello, World!"}
更多推荐





所有评论(0)