springfox-boot-starter最新版本号为3.0.0,能够很好的集成swagger3到springboot项目中,但开局即巅峰,进入21年后,springfox就再没有更新维护,目前存在不少问题,且与spring-webmvc >= 5.3版本不兼容,springboot版本升级后会出现NPE错误。为了api文档能持续使用,在查询相关资料后发现springdoc-openapi能够很好的替换springfox。
springdoc-openapi官网地址:https://springdoc.org/,代码仓库:https://github.com/springdoc/springdoc-openapi
springboot版本:2.6.14
pom.xml依赖:
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.6.14</version>
</dependency>
配置(具体参考官网配置说明):
springdoc:
api-docs:
enabled: true # 生产环境需要关闭
packages-to-scan: com.zhi.demo.controller # 扫描包,默认*
paths-to-match: /* # 路径匹配,默认/*
ApiInfo配置:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;
/**
* 自定义样式属性
*
* @author 张某人
* @since 2023年3月1日14:23:32
*
*/
@Configuration
public class SwaggerConfig {
@Bean
public OpenAPI customOpenAPI() {
Contact contact = new Contact().name("张某人").email("zhi.leaf@foxmail.com");
License license = new License().name("Apache 2.0").url("http://www.apache.org/licenses/LICENSE-2.0");
Info info = new Info().title("接口文档").description("企业版").version("1.0").contact(contact).license(license);
return new OpenAPI().info(info);
}
}
API描述样例:
@RestController
@RequestMapping
public class UserController {
@Operation(summary = "根据ID获取用户信息")
@GetMapping("get")
public ResponseData<User> get(
@Parameter(description = "人员ID", required = true) @RequestParam(required = true) Integer id) {
ResponseData<User> result = new ResponseData<>();
return result;
}
@Operation(summary = "分页查询用户信息")
@PostMapping("page")
public ResponseData<List<User>> page(@Parameter(name = "分页查询条件") @RequestBody PageQueryParams params) {
ResponseData<List<User>> result = new ResponseData<>();
return result;
}
}
@Schema(description = "分页查询条件")
public class PageQueryParams {
@Parameter(allowEmptyValue = true)
@Schema(description = "分页大小", example = "10", requiredMode = RequiredMode.REQUIRED)
private Integer pageSize;
@Schema(description = "页号", defaultValue = "0")
private Integer pageNum = 0;
}
效果:
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步