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 小时前
基于springboot的在线教育系统
java·spring boot·毕业设计·课程设计·在线教育系统·源代码
小马爱打代码2 小时前
SpringBoot原生实现分布式MapReduce计算
spring boot·分布式·mapreduce
iuyou️2 小时前
Spring Boot知识点详解
java·spring boot·后端
一弓虽2 小时前
SpringBoot 学习
java·spring boot·后端·学习
来自星星的猫教授4 小时前
spring,spring boot, spring cloud三者区别
spring boot·spring·spring cloud
乌夷5 小时前
使用spring boot vue 上传mp4转码为dash并播放
vue.js·spring boot·dash
A阳俊yi7 小时前
Spring Boot日志配置
java·spring boot·后端
苹果酱05677 小时前
2020-06-23 暑期学习日更计划(机器学习入门之路(资源汇总)+概率论)
java·vue.js·spring boot·mysql·课程设计
斜月7 小时前
一个服务预约系统该如何设计?
spring boot·后端
Java水解8 小时前
线程池详解:在SpringBoot中的最佳实践
spring boot·后端