背景
SpringBoot
升级为3.x
后,包javax
下的所有内容都迁移到了jakarta
下,比如HttpServletRequest
, 而swagger
还是使用的包javax
, 导致出现不兼容的问题,因此可以使用springdoc
来替代以前的swagger
官网资料
https://springdoc.org/v2/index.html
引入依赖pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
</dependency>
</dependencies>
示例Controller
@RestController
public class DemoController {
@Operation(summary = "示例",description = "示例描述")
@RequestMapping(path = "/demo", method = RequestMethod.GET)
public String demo(String name) {
return "Hello," + name;
}
}
生成的文档效果
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-N8vwkx2E-1682830067731)(./assets/【SpringBoot】最新版3.x集成springdoc代替Swagger-1682781287108.png)]
配置类与配置文件
以上是默认行为生成的效果,已经基本可以满足我们的需要,也可以通过配置类和配置文件定义更多特性
配置文件
springdoc:
packages-to-scan: ##需要扫描的包,可以配置多个
- com.wen3.springdoc.demo.controller
paths-to-exclude: ##配置不包含在swagger文档中的api
- /api/test/**
- /api/mockito/data
swagger-ui:
enabled: true #开启/禁止swagger,prod可以设置为false
path: /swagger-ui.html #swagger页面
api-docs:
enabled: true #开启/禁止api-docs, prod可以设置为false
path: /api-docs #api的json文档
use-management-port: false
配置类
package com.wen3.springdoc.demo.autoconfigure;
import io.swagger.v3.oas.models.ExternalDocumentation;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author tangheng
*/
@Configuration
public class SpringDocAutoConfiguration {
@Bean
public OpenAPI openAPI(){
return new OpenAPI()
.info(apiInfo())
.externalDocs(new ExternalDocumentation()
.description("SpringDoc Wiki Documentation")
.url("https://springdoc.org/v2"));
}
private Info apiInfo() {
return new Info()
.title("Wen3 Demo API Doc")
.description("springfox swagger 3.0 demo")
.version("1.0.0")
.contact(new Contact()
.name("demo")
.url("www.demo.com")
.email("demo@demo.com")
)
.license(new License()
.name("Apache 2.0")
.url("http://www.apache.org/licenses/LICENSE-2.0.txt")
);
}
}
常用的swagger注解和springdoc的对应关系
SpringFox | SpringDoc |
---|---|
@Api | @Tag |
@ApiIgnore | @Parameter(hidden = true) @Operation(hidden = true) @Hidden |
@ApiImplicitParam | @Parameter |
@ApiImplicitParams | @Parameters |
@ApiModel | @Schema |
@ApiModelProperty | @Schema |
@ApiOperation(value=“示例”, notes=“示例描述”) | @Operation(summary=“示例”,description=“示例描述”) |
@ApiParam | @Parameter |
@ApiResponse(code=404, message=“Not Found”) | @ApiResponse(responseCode=“404”, description=“Not Found”) |