文档
Java Hello World — Spring Boot REST API
目标
用 Spring Boot 3 创建一个 RESTful Web 服务,返回 JSON 格式的 "Hello World"。
完整代码
// HelloWorldApplication.java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.Instant;
import java.util.Map;
@SpringBootApplication
public class HelloWorldApplication {
public static void main(String[] args) {
SpringApplication.run(HelloWorldApplication.class, args);
}
}
@RestController
class HelloController {
@GetMapping("/")
public Map<String, Object> hello() {
return Map.of(
"message", "Hello World",
"timestamp", Instant.now().getEpochSecond()
);
}
@GetMapping("/health")
public Map<String, String> health() {
return Map.of("status", "ok");
}
}
运行步骤
方式一:Spring Initializr (推荐)
# 1. 访问 https://start.spring.io
# 2. 选 Maven / Java / Spring Boot 3.4+ / Java 21
# 3. 添加依赖: Spring Web
# 4. 下载解压,将上述代码复制到 src/main/java/com/example/demo/
# 5. 运行
./mvnw spring-boot:run # macOS/Linux
mvnw.cmd spring-boot:run # Windows
方式二:Maven 手动创建
<!-- pom.xml -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.4.0</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
测试
curl http://localhost:8080/
# 输出: {"message":"Hello World","timestamp":1717000000}
curl http://localhost:8080/health
# 输出: {"status":"ok"}
预期输出
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v3.4.0)
...
Tomcat started on port 8080
要点说明
@SpringBootApplication组合了@Configuration、@EnableAutoConfiguration、@ComponentScan@RestController=@Controller+@ResponseBody(返回 JSON 而非视图)Map.of()是 JDK 9+ 工厂方法,创建不可变 Map- Spring Boot 内嵌 Tomcat,无需部署 war 包