原创

Spring Boot 文档示例

温馨提示:
本文最后更新于 2024年07月23日,已超过 252 天没有更新。若文章内的图片失效(无法正常加载),请留言反馈或直接联系我

Spring Boot 文档示例

概述

本文档概述了如何使用 Spring Boot 构建一个简单的 RESTful Web 服务。

项目结构

└── src └── main └── java └── com └── example └── springboot └── Application.java └── GreetingController.java

Application.java

```java package com.example.springboot;

import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication public class Application {

public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
}

} ```

GreetingController.java

```java package com.example.springboot;

import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController;

@RestController public class GreetingController {

@GetMapping("/greeting")
public String greeting() {
    return "Hello, Spring Boot!";
}

} ```

运行应用程序

  1. 在命令行中导航到项目根目录。
  2. 运行以下命令: bash mvn spring-boot:run

访问 API

启动应用程序后,可以通过以下 URL 访问 API:

http://localhost:8080/greeting

该请求将返回以下 JSON 数据:

json "Hello, Spring Boot!"

依赖项

以下 Maven 依赖项用于此示例项目:

xml <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>

结论

本文档演示了如何使用 Spring Boot 构建一个简单的 RESTful Web 服务。您可以扩展此示例,以构建更复杂的功能,例如数据库访问、安全性、消息队列等。

正文到此结束