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 集成 MyBatis-Plus 全攻略
java·spring boot·mybatis
javachen__2 小时前
SpringBoot整合P6Spy实现全链路SQL监控
spring boot·后端·sql
IT毕设实战小研8 小时前
基于Spring Boot 4s店车辆管理系统 租车管理系统 停车位管理系统 智慧车辆管理系统
java·开发语言·spring boot·后端·spring·毕业设计·课程设计
一只爱撸猫的程序猿9 小时前
使用Spring AI配合MCP(Model Context Protocol)构建一个"智能代码审查助手"
spring boot·aigc·ai编程
甄超锋9 小时前
Java ArrayList的介绍及用法
java·windows·spring boot·python·spring·spring cloud·tomcat
武昌库里写JAVA12 小时前
JAVA面试汇总(四)JVM(一)
java·vue.js·spring boot·sql·学习
Pitayafruit13 小时前
Spring AI 进阶之路03:集成RAG构建高效知识库
spring boot·后端·llm
zru_960213 小时前
Spring Boot 单元测试:@SpyBean 使用教程
spring boot·单元测试·log4j
甄超锋13 小时前
Java Maven更换国内源
java·开发语言·spring boot·spring·spring cloud·tomcat·maven
还是鼠鼠14 小时前
tlias智能学习辅助系统--Maven 高级-私服介绍与资源上传下载
java·spring boot·后端·spring·maven