文档
Spring Boot Hello World REST API
目标
创建一个最简单的 Spring Boot REST API,返回 "Hello, World!" JSON 响应。
完整代码
1. 主应用类 DemoApplication.java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
2. REST 控制器 HelloController.java
package com.example.demo.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello, World!";
}
@GetMapping("/hello/json")
public Greeting greeting(@RequestParam(defaultValue = "World") String name) {
return new Greeting("Hello, " + name + "!");
}
}
class Greeting {
private String message;
public Greeting(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
3. 配置文件 application.properties
server.port=8080
spring.application.name=demo
运行步骤
# Maven
./mvnw spring-boot:run
# Gradle
./gradlew bootRun
# 或打包运行
./mvnw clean package -DskipTests
java -jar target/demo-0.0.1-SNAPSHOT.jar
测试
# 测试纯文本
curl http://localhost:8080/hello
# 输出: Hello, World!
# 测试 JSON
curl http://localhost:8080/hello/json?name=SpringBoot
# 输出: {"message":"Hello, SpringBoot!"}
预期输出
启动日志关键行:
Started DemoApplication in 1.234 seconds (process running for 1.5)
访问接口返回 200 OK,响应体为 Hello, World!。