SpringBoot开发——整合SpringDoc实现在线接口文档

文章目录

  • 1、什么是SpringDoc?
  • 2、环境准备
  • 3、添加依赖
  • 4、配置SpringDoc
  • 5、编写Controller
  • 6、运行项目
  • 7、自定义API文档
  • 8、安全配置
  • 9、结论

现代Web开发中,API文档是一个至关重要的部分。它不仅可以帮助开发者理解和使用API,还可以提高开发效率,减少沟通成本。在Java生态系统中,SpringBoot是一个非常流行的框架,而SpringDoc则是一个用于生成OpenAPI规范的工具。本文将介绍如何在SpringBoot 3项目中整合SpringDoc,以实现在线接口文档的生成和展示。

1、什么是SpringDoc?

SpringDoc是一个自动生成API文档的工具,基于OpenAPI 3规范。它能够扫描SpringBoot项目中的注解,自动生成详尽的API文档,并提供一个Web界面供用户查看和测试APISpringDoc取代了Swagger 2,提供了更现代化的解决方案,并支持最新的SpringBoot版本。

2、环境准备

在开始之前,我们需要确保以下环境已经搭建完毕:

  • JDK 11或以上版本
  • Maven 3.6或以上版本
  • 一个Spring Boot 3项目

3、添加依赖

首先,我们需要在pom.xml文件中添加SpringDoc的依赖。打开pom.xml文件,并在dependencies标签中添加以下内容:

xml 复制代码
<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    <version>2.0.0</version>
</dependency>

4、配置SpringDoc

SpringDoc几乎不需要额外的配置,添加依赖后,它会自动扫描项目中的Controller并生成相应的API文档。不过,我们可以在application.properties或application.yml中进行一些基本的配置。

application.properties中添加以下配置:

bash 复制代码
springdoc.api-docs.path=/api-docs
springdoc.swagger-ui.path=/swagger-ui.html

这些配置指定了API文档Swagger UI界面的访问路径。

5、编写Controller

接下来,我们编写一个简单的Controller来演示SpringDoc的功能。创建一个名为UserController的类,并添加以下代码:

java 复制代码
package com.example.demo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.model.User;

@RestController
public class UserController {

    @GetMapping("/users/{id}")
    public User getUserById(@PathVariable Long id) {
        return new User(id, "John Doe");
    }

    @GetMapping("/users")
    public User getUserByUsername(@RequestParam String username) {
        return new User(1L, username);
    }
}

我们定义了两个API接口:一个通过用户ID获取用户信息,另一个通过用户名获取用户信息。

6、运行项目

启动SpringBoot应用程序,打开浏览器并访问http://localhost:8080/swagger-ui.html。你将看到一个自动生成的Swagger UI界面,其中包含我们刚才定义的API接口。你可以在这个界面中测试API,查看请求和响应的详细信息。

7、自定义API文档

尽管SpringDoc能够自动生成API文档,但有时候我们需要自定义文档内容,比如添加描述、标签、参数说明等。我们可以使用Swagger注解来实现这些自定义需求。

修改UserController,添加Swagger注解

java 复制代码
package com.example.demo.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.model.User;

@RestController
@Tag(name = "User Controller", description = "Operations related to users")
public class UserController {

    @GetMapping("/users/{id}")
    @Operation(summary = "Get user by ID", description = "Returns a single user by ID")
    public User getUserById(@Parameter(description = "ID of the user to be fetched") @PathVariable Long id) {
        return new User(id, "John Doe");
    }

    @GetMapping("/users")
    @Operation(summary = "Get user by username", description = "Returns a single user by username")
    public User getUserByUsername(@Parameter(description = "Username of the user to be fetched") @RequestParam String username) {
        return new User(1L, username);
    }
}

现在,当你重新访问http://localhost:8080/swagger-ui.html时,你会看到API文档中添加了描述信息,帮助用户更好地理解每个接口的功能和参数。

8、安全配置

在实际项目中,API通常需要进行安全保护。我们可以结合Spring Security来实现这一点,并配置SpringDoc使其适应安全配置。

首先,添加Spring Security依赖:

xml 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

然后,创建一个安全配置类:

java 复制代码
package com.example.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .antMatchers("/swagger-ui.html", "/api-docs/**", "/swagger-ui/**").permitAll()
            .anyRequest().authenticated()
            .and()
            .formLogin()
            .and()
            .httpBasic();
        return http.build();
    }
}

这个配置类允许未认证的用户访问Swagger UIAPI文档,同时保护其他API接口

9、结论

通过整合SpringBoot 3SpringDoc,我们可以轻松生成和管理API文档,为开发和维护提供极大便利。本文介绍了SpringDoc的基本使用方法以及如何进行自定义配置和安全保护。随着项目的不断发展,及时更新和维护API文档能够大幅提升开发效率,减少沟通成本,并提高项目的整体质量。

无论是团队协作还是对外公开API,良好的文档都是不可或缺的一部分。希望本文能够帮助你在SpringBoot项目中更好地使用SpringDoc,创建高质量的API文档

相关推荐
用生命在耍帅ㅤ1 小时前
java spring boot 动态添加 cron(表达式)任务、动态添加停止单个cron任务
java·开发语言·spring boot
程序员-珍1 小时前
SpringBoot v2.6.13 整合 swagger
java·spring boot·后端
徐*红2 小时前
springboot使用minio(8.5.11)
java·spring boot·spring
骆晨学长2 小时前
基于springboot的智慧社区微信小程序
java·数据库·spring boot·后端·微信小程序·小程序
Flying_Fish_roe3 小时前
Spring Boot-Session管理问题
java·spring boot·后端
赚钱给孩子买茅台喝3 小时前
智能BI项目第四期
java·spring boot·spring cloud·aigc
hai405873 小时前
Spring Boot中的响应与分层解耦架构
spring boot·后端·架构
工业甲酰苯胺5 小时前
Spring Boot 整合 MyBatis 的详细步骤(两种方式)
spring boot·后端·mybatis
bjzhang757 小时前
SpringBoot开发——集成Tess4j实现OCR图像文字识别
spring boot·ocr·tess4j