springboot集成swagger,自动生成接口文档
1.引入swagger的自动装配依赖的starter架包
<!--swagger 扩展工具--> <dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId> <version>4.1.0</version> </dependency>
自动装配原理:https://blog.csdn.net/a1405/article/details/123177177
2.通过spring java config配置swagger
package com.springweb.demo.config; import cn.hutool.core.util.RandomUtil; import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.info.Info; import io.swagger.v3.oas.models.info.License; import org.springdoc.core.customizers.GlobalOpenApiCustomizer; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.HashMap; import java.util.Map; /** * 引入接口文档 swagger 配置 */ @Configuration @EnableKnife4j @ConditionalOnProperty(prefix = "swagger", value = {"enable"}, havingValue = "true") public class SwaggerConfig { /** * 根据@Tag 上的排序,写入x-order * * @return the global open api customizer */ @Bean public GlobalOpenApiCustomizer orderGlobalOpenApiCustomizer() { return openApi -> { if (openApi.getTags() != null) { openApi.getTags().forEach(tag -> { Map<String, Object> map = new HashMap<>(); map.put("x-order", RandomUtil.randomInt(0, 100)); tag.setExtensions(map); }); } if (openApi.getPaths() != null) { openApi.addExtension("x-test123", "333"); openApi.getPaths().addExtension("x-abb", RandomUtil.randomInt(1, 100)); } }; } @Bean public OpenAPI customOpenAPI() { return new OpenAPI().info( new Info().title("spring-web-demo的swagger文档").version("1.0") .description("swagger接口文档").termsOfService("http://localhost:8888/spring-web-demo/doc.html") .license(new License().name("Apache 2.0").url("http://doc.xiaominfo.com")) ); } }
3.接口说明的配置。
@Tag(name = "实例功能") controller汇总说明
@ApiSort(1) 排序
@Operation(summary = "输出hello", description = "hello接口", method = "GET") 具体接口的说明
@ApiOperationSupport(order = 1) 排序
@ApiOperationSupport(order = 1) 排序
package com.springweb.demo.controller; import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport; import com.github.xiaoymin.knife4j.annotations.ApiSort; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/hello") @ApiSort(1) @Tag(name = "实例功能") public class HelloController { @GetMapping("/helloString") @ResponseBody @Operation(summary = "输出hello", description = "hello接口", method = "GET") @ApiOperationSupport(order = 1) public String helloString(){ return "hello, spring-web-demo."; } }