spring boot项目的swagger文档。

依赖从spring boot的基础上增加。参考pom.xml:

  1.           <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter</artifactId>
  4. </dependency>
  5.  
  6. <dependency>
  7. <groupId>org.springframework.boot</groupId>
  8. <artifactId>spring-boot-starter-test</artifactId>
  9. <scope>test</scope>
  10. </dependency>
  11.  
  12. <!-- Swagger -->
              <!-- 文档可视化-->
  13. <dependency>
  14. <groupId>io.springfox</groupId>
  15. <artifactId>springfox-swagger-ui</artifactId>
  16. <version>2.6.1</version>
  17. </dependency>
  18. <dependency>
  19. <groupId>io.springfox</groupId>
  20. <artifactId>springfox-swagger2</artifactId>
  21. <version>2.6.1</version>
  22. </dependency>
  23. <dependency>
  24. <groupId>org.json</groupId>
  25. <artifactId>json</artifactId>
  26. </dependency>
  27. <dependency>
  28. <groupId>org.springframework.restdocs</groupId>
  29. <artifactId>spring-restdocs-mockmvc</artifactId>
  30. <scope>test</scope>
  31. </dependency>
  32. <dependency>
  33. <groupId>io.springfox</groupId>
  34. <artifactId>springfox-staticdocs</artifactId>
  35. <version>2.6.1</version>
  36. </dependency>
  37. <dependency>
  38. <groupId>com.alibaba</groupId>
  39. <artifactId>fastjson</artifactId>
  40. <version>1.2.8</version>
  41. </dependency>

  maven插件:

  1. <build>
  2. <plugins>
  3. <plugin>
  4. <groupId>org.springframework.boot</groupId>
  5. <artifactId>spring-boot-maven-plugin</artifactId>
  6. </plugin>
  7. <plugin>
  8. <groupId>org.apache.maven.plugins</groupId>
  9. <artifactId>maven-surefire-plugin</artifactId>
  10. <configuration>
  11. <includes>
  12. <include>**/*Documentation.java</include>
  13. </includes>
  14. </configuration>
  15. </plugin>
  16. <plugin>
  17. <groupId>org.asciidoctor</groupId>
  18. <artifactId>asciidoctor-maven-plugin</artifactId>
  19. <version>1.5.3</version>
  20.  
  21. <!-- Configure generic document generation settings -->
  22. <configuration>
  23. <sourceDirectory>${project.basedir}/target/asciidoc</sourceDirectory>
  24. <sourceDocumentName>paths.adoc</sourceDocumentName>
  25. <attributes>
  26. <doctype>book</doctype>
  27. <toc>left</toc>
  28. <toclevels>3</toclevels>
  29. <numbered></numbered>
  30. <hardbreaks></hardbreaks>
  31. <sectlinks></sectlinks>
  32. <sectanchors></sectanchors>
  33. <generated>${project.build.directory}/asciidoc</generated>
  34. </attributes>
  35. </configuration>
  36. <!-- Since each execution can only handle one backend, run
  37. separate executions for each desired output type -->
  38. <executions>
  39. <execution>
  40. <id>output-html</id>
  41. <phase>test</phase>
  42. <goals>
  43. <goal>process-asciidoc</goal>
  44. </goals>
  45. <configuration>
  46. <backend>html5</backend>
  47. <outputDirectory>${project.basedir}/docs/asciidoc/html</outputDirectory>
  48. </configuration>
  49. </execution>
  50. </executions>
  51. </plugin>
  52. </plugins>
  53. </build>

  

Swagger2.java参考代码:

  1. import java.util.ArrayList;
  2.  
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.ComponentScan;
  5. import org.springframework.context.annotation.Configuration;
  6. import org.springframework.web.bind.annotation.RequestMethod;
  7.  
  8. import springfox.documentation.builders.ApiInfoBuilder;
  9. import springfox.documentation.builders.PathSelectors;
  10. import springfox.documentation.builders.RequestHandlerSelectors;
  11. import springfox.documentation.builders.ResponseMessageBuilder;
  12. import springfox.documentation.schema.ModelRef;
  13. import springfox.documentation.service.ApiInfo;
  14. import springfox.documentation.service.ResponseMessage;
  15. import springfox.documentation.spi.DocumentationType;
  16. import springfox.documentation.spring.web.plugins.Docket;
  17. import springfox.documentation.swagger2.annotations.EnableSwagger2;
  18.  
  19. @Configuration
  20. @ComponentScan
  21. @EnableSwagger2
  22. public class Swagger2 {
  23.  
  24. @Bean
  25. public Docket petApi() {
  26.  
  27. //自定义异常信息
  28. ArrayList<ResponseMessage> responseMessages = new ArrayList<ResponseMessage>() {{
  29. add(new ResponseMessageBuilder().code(200).message("成功").build());
  30. add(new ResponseMessageBuilder().code(400).message("请求参数错误").responseModel(new ModelRef("Error")).build());
  31. add(new ResponseMessageBuilder().code(401).message("权限认证失败").responseModel(new ModelRef("Error")).build());
  32. add(new ResponseMessageBuilder().code(403).message("请求资源不可用").responseModel(new ModelRef("Error")).build());
  33. add(new ResponseMessageBuilder().code(404).message("请求资源不存在").responseModel(new ModelRef("Error")).build());
  34. add(new ResponseMessageBuilder().code(409).message("请求资源冲突").responseModel(new ModelRef("Error")).build());
  35. add(new ResponseMessageBuilder().code(415).message("请求格式错误").responseModel(new ModelRef("Error")).build());
  36. add(new ResponseMessageBuilder().code(423).message("请求资源被锁定").responseModel(new ModelRef("Error")).build());
  37. add(new ResponseMessageBuilder().code(500).message("服务器内部错误").responseModel(new ModelRef("Error")).build());
  38. add(new ResponseMessageBuilder().code(501).message("请求方法不存在").responseModel(new ModelRef("Error")).build());
  39. add(new ResponseMessageBuilder().code(503).message("服务暂时不可用").responseModel(new ModelRef("Error")).build());
  40. add(new ResponseMessageBuilder().code(-1).message("未知异常").responseModel(new ModelRef("Error")).build());
  41. }};
  42. return new Docket(DocumentationType.SWAGGER_2)
  43. .apiInfo(apiInfo())
  44. .select()
  45. .apis(RequestHandlerSelectors.basePackage("my.product.controller"))//扫描的API包
  46. .paths(PathSelectors.any())
  47. .build()
  48. .useDefaultResponseMessages(false)
  49. .globalResponseMessage(RequestMethod.GET, responseMessages)
  50. .globalResponseMessage(RequestMethod.POST, responseMessages)
  51. .globalResponseMessage(RequestMethod.PUT, responseMessages)
  52. .globalResponseMessage(RequestMethod.DELETE, responseMessages);
  53. }
  54. private ApiInfo apiInfo() {
  55. return new ApiInfoBuilder()
  56. .title("Spring cloud 中使用Swagger2构建Restful APIs")
  57. .description("swagger项目文档测试说明")
  58. .version("1.0").build();
  59. }
  60.  
  61. }

  TestController.java参考代码

  1. import org.springframework.http.MediaType;
  2. import org.springframework.web.bind.annotation.RequestBody;
  3. import org.springframework.web.bind.annotation.RequestMapping;
  4. import org.springframework.web.bind.annotation.RequestMethod;
  5. import org.springframework.web.bind.annotation.RequestParam;
  6. import org.springframework.web.bind.annotation.RestController;
  7.  
  8. import io.swagger.annotations.Api;
  9. import io.swagger.annotations.ApiOperation;
  10.  
  11. @Api(value = "学生信息查询", description = "学生基本信息操作API", tags = "StudentApi", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
  12. @RestController
  13. public class Swagger2TestController {
  14.  
  15. @ApiOperation(value = "getStudent", notes = "依据学生姓名查询学生信息")
  16. @RequestMapping(value = "student", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
  17. public Student getStudent(@RequestParam("name") String name){
  18. System.out.println("name : "+name);
  19. Student reponse = new Student();
  20. reponse.setId(1);
  21. reponse.setName(name);
  22. reponse.setAge(12);
  23. reponse.setCls("二年级");
  24. reponse.setAddress("重庆市大竹林");
  25. reponse.setSex("男");
  26. return reponse;
  27. }
  28.  
  29. @ApiOperation(value = "addStudent", notes = "添加一个学生", code = 201)
  30. @RequestMapping(value = "addStudent", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
  31. public void addStudent(@RequestBody Student student){
  32. System.out.println("addStudent : "+student);
  33. return ;
  34. }
  35.  
  36. }

  student.java参考代码

  1. import io.swagger.annotations.ApiModel;
  2. import io.swagger.annotations.ApiModelProperty;
  3.  
  4. @ApiModel(value = "Student", description = "学生信息描述")
  5. public class Student {
  6.  
  7. /**
  8. * 学号
  9. */
  10. @ApiModelProperty("学号")
  11. private int id;
  12. /**
  13. * 姓名
  14. */
  15. @ApiModelProperty("姓名")
  16. private String name;
  17. /**
  18. * 年龄
  19. */
  20. @ApiModelProperty("年龄")
  21. private int age;
  22. /**
  23. * 性别
  24. */
  25. @ApiModelProperty("性别")
  26. private String sex;
  27. /**
  28. * 班级
  29. */
  30. @ApiModelProperty("班级")
  31. private String cls;
  32. /**
  33. * 住址
  34. */
  35. @ApiModelProperty("家庭住址")
  36. private String address;
  37. public int getId() {
  38. return id;
  39. }
  40. public void setId(int id) {
  41. this.id = id;
  42. }
  43. public String getName() {
  44. return name;
  45. }
  46. public void setName(String name) {
  47. this.name = name;
  48. }
  49. public int getAge() {
  50. return age;
  51. }
  52. public void setAge(int age) {
  53. this.age = age;
  54. }
  55. public String getSex() {
  56. return sex;
  57. }
  58. public void setSex(String sex) {
  59. this.sex = sex;
  60. }
  61. public String getCls() {
  62. return cls;
  63. }
  64. public void setCls(String cls) {
  65. this.cls = cls;
  66. }
  67. public String getAddress() {
  68. return address;
  69. }
  70. public void setAddress(String address) {
  71. this.address = address;
  72. }
  73.  
  74. }

  测试类:

  1. import org.junit.After;
  2. import org.junit.Test;
  3. import org.junit.runner.RunWith;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs;
  6. import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
  7. import org.springframework.boot.test.context.SpringBootTest;
  8. import org.springframework.http.MediaType;
  9. import org.springframework.restdocs.mockmvc.MockMvcRestDocumentation;
  10. import org.springframework.test.context.junit4.SpringRunner;
  11. import org.springframework.test.web.servlet.MockMvc;
  12.  
  13. import com.alibaba.fastjson.JSON;
  14. import com.swagger.model.Student;
  15.  
  16. import io.github.robwin.markup.builder.MarkupLanguage;
  17. import io.github.robwin.swagger2markup.GroupBy;
  18. import io.github.robwin.swagger2markup.Swagger2MarkupConverter;
  19. import springfox.documentation.staticdocs.SwaggerResultHandler;
  20. import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get;
  21. import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint;
  22. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
  23. import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse;
  24. import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.post;
  25.  
  26. @AutoConfigureMockMvc
  27. @AutoConfigureRestDocs(outputDir = "target/generated-snippets")
  28. @RunWith(SpringRunner.class)
  29. @SpringBootTest
  30. public class SwaggerApplicationTests {
  31.  
  32. private String snippetDir = "target/generated-snippets";
  33. private String outputDir = "target/asciidoc";
  34.  
  35. @Autowired
  36. private MockMvc mockMvc;
  37.  
  38. @After
  39. public void Test() throws Exception{
  40. // 得到swagger.json,写入outputDir目录中
  41. mockMvc.perform(get(Swagger2Controller.DEFAULT_URL).accept(MediaType.APPLICATION_JSON))
  42. .andDo(SwaggerResultHandler.outputDirectory(outputDir).build())
  43. .andExpect(status().isOk())
  44. .andReturn();
  45.  
  46. // 读取上一步生成的swagger.json转成asciiDoc,写入到outputDir
  47. // 这个outputDir必须和插件里面<generated></generated>标签配置一致
  48. Swagger2MarkupConverter.from(outputDir + "/swagger.json")
  49. .withPathsGroupedBy(GroupBy.TAGS)// 按tag排序
  50. .withMarkupLanguage(MarkupLanguage.ASCIIDOC)// 格式
  51. .withExamples(snippetDir)
  52. .build()
  53. .intoFolder(outputDir);// 输出
  54. }
  55. @Test
  56. public void contextLoads() throws Exception {
  57. mockMvc.perform(get("/student").param("name", "xxx")
  58. .accept(MediaType.APPLICATION_JSON))
  59. .andExpect(status().isOk())
  60. .andDo(MockMvcRestDocumentation.document("getStudent", preprocessResponse(prettyPrint())));
  61.  
  62. Student student = new Student();
  63. student.setName("xxx");
  64. student.setAge(23);
  65. student.setAddress("湖北麻城");
  66. student.setCls("二年级");
  67. student.setSex("男");
  68.  
  69. mockMvc.perform(post("/addStudent").contentType(MediaType.APPLICATION_JSON)
  70. .content(JSON.toJSONString(student))
  71. .accept(MediaType.APPLICATION_JSON))
  72. .andExpect(status().is2xxSuccessful())
  73. .andDo(MockMvcRestDocumentation.document("addStudent", preprocessResponse(prettyPrint())));
  74. }
  75.  
  76. }

  每个API都需要测试一下才有效。测试完后直接install,这离线文档就会在${product.path}\docs\asciidoc\html下生成。

在线文档启动项目访问http://localhost:8080/swagger-ui.html就行了。springboot启动类加@EnableSwagger2 注解就行

swagger在线文档和离线文档的更多相关文章

  1. Swagger接口如何生成Html离线文档

    A very simple tool that converts Swagger Api Document to Html File. 小记Swagger接口生成Html离线文档 由来 很多人用swa ...

  2. spring boot利用swagger和spring doc生成在线和离线文档

    参考博客地址: 在线文档:http://blog.didispace.com/springbootswagger2/ 离线文档:http://www.jianshu.com/p/af7a6f29bf4 ...

  3. 在.Net Core WebAPI下给Swagger增加导出离线文档功能

    一丶前言 最近刚接触到Swagger,在github上下载了它的源码和demo学习了一遍,发现这个组件非常好用,不过不足的是它没有导出离线文档的功能,于是乎我就想给它加一个导出功能 Swagger G ...

  4. JDK8 API离线文档免费下载&JavaEE API文档离线下载&API在线查看链接&常用的JAR包下载

    1.JDK8 API离线文档 链接:https://pan.baidu.com/s/1fYc-QesmYRumTEPmnSgEKA 提取码:2bdr 2.JavaEE API文档离线下载 链接:htt ...

  5. Swagger在线文档使用教程

    springboot整合Swagger2 1.首先创建一个springboot工程,在pom文件内导入依赖   <!--swagger依赖-->      <!--Swagger2- ...

  6. cocos2d-x3.6 生成带类图的离线文档

    我的博客:http://blog.csdn.net/dawn_moon cocos2d-x的官网有点慢,并且最新3.6的在线API文档居然没有了类图,不知道什么原因,之前2.2.6都是有的. 只是能够 ...

  7. 使用swagger作为restful api的doc文档生成

    初衷 记得以前写接口,写完后会整理一份API接口文档,而文档的格式如果没有具体要求的话,最终展示的文档则完全决定于开发者的心情.也许多点,也许少点.甚至,接口总是需要适应新需求的,修改了,增加了,这份 ...

  8. Java实现office文档与pdf文档的在线预览功能

    最近项目有个需求要java实现office文档与pdf文档的在线预览功能,刚刚接到的时候就觉得有点难,以自己的水平难以在三四天做完.压力略大.后面查找百度资料.以及在同事与网友的帮助下,四天多把它做完 ...

  9. 如何解决Android SDK中离线文档打开慢的问题

    原文:http://blog.csdn.net/hansel/article/details/39268511 Android SDK中的离线文档虽然都是本地文件,但是有很多Javascript, C ...

随机推荐

  1. 解决启动WebLogic输入用户名密码问题

    转自:http://wenku.baidu.com/link?url=M6wJDVwm_Us6NsYi5u-PDTTbTHpO_ncsv5yClXSxhDIhA70IRga5ZdvotT4bW__MG ...

  2. 浏览器开发调试工具的秘密 - Secrets of the Browser Developer Tools

    来源:GBin1.com 如果你是一个前端开发人员的话,正确的了解和使用浏览器开发工具是一个必须的技能. Secrets of the Browser Developer Tools是一个帮助大家了解 ...

  3. 超棒的JS移动设备滑动内容幻灯实现 - Swiper

    来源:GBin1.com 在线演示 如果你需要一款帮助你实现手机或者移动设备上内容幻灯实现的JS类库的话 , Swiper是一个不错的选择,它不依赖于任何第三方的类库.因此体积非常小,适合运行在移动设 ...

  4. 算法笔记_078:蓝桥杯练习 最大最小公倍数(Java)

    目录 1 问题描述 2 解决方案   1 问题描述 问题描述 已知一个正整数N,问从1~N中任选出三个数,他们的最小公倍数最大可以为多少. 输入格式 输入一个正整数N. 输出格式 输出一个整数,表示你 ...

  5. PyQt4的一些问题汇总

    (1)PyQt4获取中文路径名字乱码问题 网址可以参见:http://permalink.gmane.org/gmane.comp.python.chinese/9916 处理方式的代码可以参考如下 ...

  6. canvas贝济埃曲线

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...

  7. 【VB编程】05.MsgBox与InputBox函数

    在VBA程序中,数据的输入输出是通过函数实现的,其实现的方式是通过对话框的形式表示出来的.例如MsgBox,Inputbox等,不要误认为是输入输出语句的关键字,其实仅仅是一个普通函数而已. [Msg ...

  8. Redis主从配置及通过Keepalived实现Redis自动切换高可用

    Redis主从配置及通过Keepalived实现Redis自动切换高可用 [日期:2014-07-23] 来源:Linux社区  作者:fuquanjun [字体:大 中 小]   一:环境介绍: M ...

  9. python --存储对象

    转自:http://www.cnblogs.com/vamei/archive/2012/09/15/2684781.html 在之前对Python对象的介绍中 (面向对象的基本概念,面向对象的进一步 ...

  10. C++的多态例子

    1.多态的例子 题目: 某小型公司,主要有四类员工(Employee):经理(Manager).技术人员(Technician).销售经理(SalesManager)和推销员(SalesMan).现在 ...