Java, 原创, 服务器, , ,

Spring Boot Maven Project 整合 Swagger2-3.0(OpenApi 3)方法

因目前网上流行的大部分是swagger2-2版本整合,swagger2-3.0(或称swagger3)版本较少,而且说法各异,目前根据实际项目将整合流程记录如下

分三部操作,1.引入依赖,2.开启swagger-ui, 3.整合相关Controller类

1.引入依赖

在根目录的 pom.xml中(如果分模块应该放在controller和start模块下的pom.xml中)加入下面依赖,记住 swagger2从3.0版本开始就是用 openapi了 参考地址 OpenApi 3 & Spring Boot,使用的版本 springdoc-openapi v1.4.8,放在 dependencies标签内

<!-- openapi 3 -->
<dependency>
	<groupId>org.springdoc</groupId>
	<artifactId>springdoc-openapi-ui</artifactId>
	<version>1.4.8</version>
</dependency>

2.开启swagger-ui功能

修改 application.properties 文件,新增代码

springdoc.swagger-ui.enabled=true
springdoc.api-docs.enabled=true 

3.在 Controller中添加注解

相关注解使用参考文章 OpenApi 3 & Spring Boot , Migrating from SpringFox

package cn.focusmedia.demo2.demo;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@Tag(name = "Demo测试接口")
@RestController
public class DemoController {

    @Operation(summary  = "hello xx ")
    @GetMapping("/hello")
    public String hello(@RequestParam(value="name", defaultValue="World") String name) {
        return String.format("hello %s!", name);
    }

    @Operation(summary  = "abc")
    @GetMapping("/abc")
    public String abc() {
        System.out.println("abc");
        return "abc";
    }
}

4.验证

启动服务后 打开 http://localhost:8080/swagger-ui.html 浏览器会自动跳转至 http://localhost:8080/swagger-ui/index.html?configUrl=/v3/api-docs/swagger-config

不是直接使用 http://localhost:8080/swagger-ui/index.html ,因为这里加载的是官方demo的配置,不是我们需要的。

问题

(695)

Related Post