在spring中使用Swagger2自动生成及导出API文档

您所在的位置:网站首页 文档在线导出 在spring中使用Swagger2自动生成及导出API文档

在spring中使用Swagger2自动生成及导出API文档

2024-07-11 05:26| 来源: 网络整理| 查看: 265

Swagger2可整合入spring boot或spring MVC项目,它作为一个规范和完整的框架,可以用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。它具有以下特点:

API接口文档在线自动生成,文档随接口变动实时更新,节省维护成本支持在线测试接口,不依赖第三方工具 使用 1.在pom.xml中添加依赖 io.springfox springfox-swagger-ui 2.9.2 io.springfox springfox-swagger2 2.9.2 2.创建配置类Swagger2Configuration @Configuration @EnableSwagger2 //开启Swagger2服务 public class Swagger2Configuration { //api接口包扫描路径 private static final String SWAGGER_SCAN_BASE_PACKAGE = "cn.koyanagi.iot_em.controller"; private static final String VERSION = "1.0.0"; @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage(SWAGGER_SCAN_BASE_PACKAGE)) .paths(PathSelectors.any()) // 可以根据url路径设置哪些请求加入文档,忽略哪些请求 .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("xxx监测系统") //设置文档的标题 .description("xxx监测系统 API 接口文档") // 设置文档的描述 .version(VERSION) // 设置文档的版本信息-> 1.0.0 Version information .termsOfServiceUrl("http://www.koyanagi.cn") // 设置文档的License信息->1.3 License information .build(); } } 3.在控制器里添加Swagger2的注解来生成文档 //示例 @Api(description = "系统主接口") @Controller @RequestMapping("/main") public class MainController { @ApiOperation(value = "主页面入口", notes = "主页面入口可分页,排序") @ApiImplicitParams({ @ApiImplicitParam(name = "pageNum", value = "当前页码"), @ApiImplicitParam(name = "orderBy", value = "排序方式") }) @RequestMapping(value = {"","/{pageNum}","/{pageNum}/{orderBy}"},method = RequestMethod.GET) public ModelAndView index(ModelAndView mov, @PathVariable(value = "pageNum",required = false) String pageNum, @PathVariable(value = "orderBy",required = false) String orderBy) { //业务... return mov; } }

Swagger2的注解:

@Api:修饰整个类,描述Controller的作用

@ApiOperation:描述一个类的一个方法,或者说一个接口

@ApiParam:单个参数描述

@ApiModel:用对象来接收参数

@ApiProperty:用对象接收参数时,描述对象的一个字段

@ApiResponse:HTTP响应其中1个描述

@ApiResponses:HTTP响应整体描述

@ApiIgnore:使用该注解忽略这个API

@ApiError :发生错误返回的信息

@ApiImplicitParam:描述一个请求参数,可以配置参数的中文含义,还可以给参数设置默认值

@ApiImplicitParams:描述由多个 @ApiImplicitParam 注解的参数组成的请求参数列表

4.使用

项目启动后,访问http://localhost:8080/swagger-ui.html

Swagger2测试1

点击进入方法,还可以在线测试该方法

5.被拦截问题

如果项目有MVC拦截器,将Swagger2添加到springMVC拦截器白名单:

//WebConfigurer.java ··· @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(loginInterceptor).addPathPatterns("/**") .excludePathPatterns("/swagger-ui.html", "/v2/**", "/swagger-resources/**"); }

Spring项目中如果还集成了 Spring Security,Swagger2 文档也会被拦截。解决方法是在 Security 的配置类中重写 configure 方法添加白名单即可:

@Override public void configure ( WebSecurity web) throws Exception { web.ignoring() .antMatchers("/swagger-ui.html") .antMatchers("/v2/**") .antMatchers("/swagger-resources/**"); } 6.使用Swagger2Markup导出该在线API文档

Swagger2Markup是Github上的一个开源项目。该项目主要用来将Swagger自动生成的文档转换成几种流行的格式以便于静态部署和使用,比如:AsciiDoc、Markdown、Confluence。

项目主页:https://github.com/Swagger2Markup/swagger2markup

6.1 在pom.xml导入相关依赖 ... io.github.swagger2markup swagger2markup 1.3.1 false jcenter-releases jcenter http://jcenter.bintray.com 6.2 在单元测试类里来执行生成文档的代码 /** * 生成AsciiDocs格式文档-多个文件 * @throws Exception */ @Test public void generateAsciiDocs() throws Exception { // 输出Ascii格式 Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder() .withMarkupLanguage(MarkupLanguage.ASCIIDOC) .withOutputLanguage(Language.ZH) .withPathsGroupedBy(GroupBy.TAGS) .withGeneratedExamples() .withoutInlineSchema() .build(); Swagger2MarkupConverter.from(new URL("http://localhost:8082/v2/api-docs")) .withConfig(config) .build() .toFolder(Paths.get("src/docs/asciidoc/generated")); } /** * 生成Markdown格式文档-多个文件 * @throws Exception */ @Test public void generateMarkdownDocs() throws Exception { // 输出Markdown格式 Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder() .withMarkupLanguage(MarkupLanguage.MARKDOWN) .withOutputLanguage(Language.ZH) .withPathsGroupedBy(GroupBy.TAGS) .withGeneratedExamples() .withoutInlineSchema() .build(); Swagger2MarkupConverter.from(new URL("http://localhost:8082/v2/api-docs")) .withConfig(config) .build() .toFolder(Paths.get("src/docs/markdown/generated")); } /** * 生成Confluence格式文档 * @throws Exception */ @Test public void generateConfluenceDocs() throws Exception { // 输出Confluence使用的格式 Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder() .withMarkupLanguage(MarkupLanguage.CONFLUENCE_MARKUP) .withOutputLanguage(Language.ZH) .withPathsGroupedBy(GroupBy.TAGS) .withGeneratedExamples() .withoutInlineSchema() .build(); Swagger2MarkupConverter.from(new URL("http://localhost:8082/v2/api-docs")) .withConfig(config) .build() .toFolder(Paths.get("src/docs/confluence/generated")); } /** * 生成AsciiDocs格式文档,并汇总成一个文件 * @throws Exception */ @Test public void generateAsciiDocsToFile() throws Exception { // 输出Ascii到单文件 Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder() .withMarkupLanguage(MarkupLanguage.ASCIIDOC) .withOutputLanguage(Language.ZH) .withPathsGroupedBy(GroupBy.TAGS) .withGeneratedExamples() .withoutInlineSchema() .build(); Swagger2MarkupConverter.from(new URL("http://localhost:8082/v2/api-docs")) .withConfig(config) .build() .toFile(Paths.get("src/docs/asciidoc/generated/all")); } /** * 生成Markdown格式文档,并汇总成一个文件 * @throws Exception */ @Test public void generateMarkdownDocsToFile() throws Exception { // 输出Markdown到单文件 Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder() .withMarkupLanguage(MarkupLanguage.MARKDOWN) .withOutputLanguage(Language.ZH) .withPathsGroupedBy(GroupBy.TAGS) .withGeneratedExamples() .withoutInlineSchema() .build(); Swagger2MarkupConverter.from(new URL("http://localhost:8082/v2/api-docs")) .withConfig(config) .build() .toFile(Paths.get("src/docs/markdown/generated/all")); }

若遇到问题 java.lang.NoClassDefFoundError: org/pegdown/PegDownProcessor 修改pom.xml增加:

org.pegdown pegdown 1.4.2

选择一种文档生成方式后,再执行以下操作(只有生成ASCIIDOC格式才能执行以下操作生成HTML):

6.3 使用插件生成HTML静态资源

在pom.xml加入插件

org.asciidoctor asciidoctor-maven-plugin 1.5.6 src/docs/asciidoc/generated src/docs/asciidoc/html true book html coderay left 3 true

执行该插件的asciidoctor:process-asciidoc命令之后,就能在src/docs/asciidoc/html目录下生成最终可用的静态部署HTML了.访问:

swagger2测试2

当然也可导出为word或者pdf:

导出为word https://www.cnblogs.com/jmcui/p/8298823.html https://github.com/JMCuixy/SwaggerToWord

导出为pdf https://blog.csdn.net/qq_29534483/article/details/81227308 https://blog.csdn.net/qq_29534483/article/details/81235081



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3