使用Java生成RESTful API接口文档

1. 添加 Swagger 依赖

pom.xml 文件中添加 Swagger 依赖项:

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>

2. 配置 Swagger

src/main/java/com/example/demo/config 目录下创建一个新的配置类 SwaggerConfig.java

package com.example.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
                .paths(PathSelectors.any())
                .build();
    }
}

3. 添加注解到控制器

为了让 Swagger 识别 API,你可以在控制器类和方法上添加注解。例如,在 UserController.java 中:

package com.example.demo.controller;

import com.example.demo.model.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Api(tags = "User Management")
@RestController
@RequestMapping("/api/users")
public class UserController {

    private List<User> users = new ArrayList<>();

    @ApiOperation(value = "Get all users", notes = "Returns a list of all users")
    @GetMapping
    public List<User> getAllUsers() {
        return users;
    }

    @ApiOperation(value = "Get user by ID", notes = "Returns a single user by ID")
    @GetMapping("/{id}")
    public User getUserById(@PathVariable Long id) {
        return users.stream().filter(user -> user.getId().equals(id)).findFirst().orElse(null);
    }

    @ApiOperation(value = "Create a new user", notes = "Creates a new user and returns the created user")
    @PostMapping
    public User createUser(@RequestBody User user) {
        users.add(user);
        return user;
    }

    @ApiOperation(value = "Update an existing user", notes = "Updates a user's information by ID")
    @PutMapping("/{id}")
    public User updateUser(@PathVariable Long id, @RequestBody User updatedUser) {
        User user = getUserById(id);
        if (user != null) {
            user.setName(updatedUser.getName());
            user.setEmail(updatedUser.getEmail());
        }
        return user;
    }

    @ApiOperation(value = "Delete a user", notes = "Deletes a user by ID")
    @DeleteMapping("/{id}")
    public void deleteUser(@PathVariable Long id) {
        users.removeIf(user -> user.getId().equals(id));
    }
}

4. 访问 Swagger UI

启动 Spring Boot 应用程序后,可以通过浏览器访问 Swagger UI,通常是通过以下 URL:

http://localhost:8080/swagger-ui/

Swagger UI 是一个交互式界面,展示了所有的 API 端点和方法,你可以直接在页面上进行 API 请求测试。

5. 生成静态文档(可选)

如果你需要生成静态的 API 文档,可以使用 Swagger 的代码生成工具或其他第三方工具,例如 Swagger2Markup。通过这些工具,可以将 API 文档生成 HTML、PDF、Asciidoc 等格式的文档。

6. 配置 Swagger 文档的详细信息(可选)

如果你希望为 Swagger 文档添加更多详细信息,例如 API 标题、描述、版本等,可以在 SwaggerConfig 中添加如下配置:

import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.service.ApiInfo;

@Bean
public Docket api() {
    return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
            .paths(PathSelectors.any())
            .build()
            .apiInfo(apiInfo());
}

private ApiInfo apiInfo() {
    return new ApiInfoBuilder()
            .title("User Management API")
            .description("This API allows to perform CRUD operations on users")
            .version("1.0.0")
            .build();
}

  • 6
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

愿时光不负.

爱意随风起,风止意难平。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值