• Swagger使用


    Swagger使用

    1. Swagger UI

    按以下步骤配置,项目启动后访问:

    http://localhost:8080/swagger-ui.html

    1.1 添加依赖

     

    1. <dependency>
    2. <groupId>io.springfoxgroupId>
    3. <artifactId>springfox-swagger2artifactId>
    4. <version>2.2.2version>
    5. dependency>
    6. <dependency>
    7. <groupId>io.springfoxgroupId>
    8. <artifactId>springfox-swagger-uiartifactId>
    9. <version>2.2.2version>
    10. dependency>

    1.2 配置类

     

    1. @Configuration
    2. @EnableSwagger2
    3. public class Swagger2 {
    4. public static final String SWAGGER_SCAN_BASE_PACKAGE = "abc.boot.examples.web";
    5. public static final String VERSION = "1.0.0";
    6. @Bean
    7. public Docket createRestApi() {
    8. return new Docket(DocumentationType.SWAGGER_2)
    9. .apiInfo(apiInfo())
    10. .select()
    11. .apis(RequestHandlerSelectors.basePackage(SWAGGER_SCAN_BASE_PACKAGE))//api接口包扫描路径
    12. .paths(PathSelectors.any())//可以根据url路径设置哪些请求加入文档,忽略哪些请求
    13. .build();
    14. }
    15. private ApiInfo apiInfo() {
    16. return new ApiInfoBuilder()
    17. .title("Swagger2 接口文档示例")//设置文档的标题
    18. .description("更多内容请关注:http://www.abc.com")//设置文档的描述->1.Overview
    19. .version(VERSION)//设置文档的版本信息-> 1.1 Version information
    20. .contact(new Contact("ABC Boot", "http://www.abc.comt", ""))//设置文档的联系方式->1.2 Contact information
    21. .termsOfServiceUrl("www.abc.com")//设置文档的License信息->1.3 License information
    22. .build();
    23. }
    24. }

    1.3 注解使用

    @ApiOperation

    @ApiOperation(value="获取用户列表", notes="获取所有用户列表",produces = "application/json") @RequestMapping(value="/users", method= RequestMethod.GET) public List getUserList() { List r = new ArrayList(users.values()); return r; }

    @ApiResponses

    @ApiOperation(value="获取用户详细信息", notes="根据url的id来获取用户详细信息",produces = "application/json") // ApiResponses 增加返回结果的描述 @ApiResponses(value = {@ApiResponse(code = 405,message = "Invalid input",response = Integer.class)}) (1) @ApiImplicitParam(name = "id",value = "用户ID",dataType = "int",paramType = "path") (2) @RequestMapping(value="/users/{id}", method= RequestMethod.GET) public User getUser(@PathVariable Integer id) { return users.get(id); }

    (1) 在默认Response的基础上增加新的Response说明

    (2) 使用ApiImplicitParam描述接口参数

    @ApiImplicitParams

    @ApiOperation(value="更新用户名称", notes="更新指定用户的名称") @RequestMapping(value="/users/{id}", method= RequestMethod.POST) @ApiImplicitParams({ (1) @ApiImplicitParam(name = "id",value = "用户ID",paramType = "path",dataType = "int"), (2) @ApiImplicitParam(name = "userName",value = "用户名称",paramType = "form",dataType = "string") }) public void updateUserName(@PathVariable Integer id,@RequestParam String userName){ User u = users.get(id); u.setName(userName); }

    (1) 使用ApiImplicitParams描述多个参数

    (2) 使用ApiImplicitParam时,需要指定paramType,这样也便于swagger ui 生成参数的输入格式。

    paramType 有五个可选值 : path, query, body, header, form

    @ApiParam

    @ApiOperation(value="创建用户-传递简单对象", notes="传递简单对象",produces = "application/json") @RequestMapping(value="/users-1", method= RequestMethod.POST) //可以不加ApiParam注解,需要给参数添加描述时可以使用这个注解,或者使用ApiImplicitParams注解 (1) public Map postUser(@RequestParam String userName,@ApiParam("地址") @RequestParam(required = false) String address) { User user = new User(); user.setId(Math.round(10)); user.setName(userName); user.setAddress(address); users.put(user.getId(), user); return ImmutableMap.of("user",user); }

    (1) 使用ApiParam描述接口参数

    ApiImplicitParam 与 ApiParam 的区别

    ApiImplicitParam: This is the only way to define parameters when using Servlets or other non-JAX-RS environments.

    • 对Servlets或者非 JAX-RS的环境,只能使用 ApiImplicitParam。
    • 在使用上,ApiImplicitParam比ApiParam具有更少的代码侵入性,只要写在方法上就可以了,但是需要提供具体的属性才能配合swagger ui解析使用。
    • ApiParam只需要较少的属性,与swagger ui配合更好。

    传递复杂对象 By ModelAttribute

    @ApiOperation(value="创建用户-传递复杂对象", notes="传递复杂对象DTO, url参数拼接",produces = "application/json") @RequestMapping(value="/users-2", method= RequestMethod.POST) //传递对象推荐使用ModelAttribute注解 public Map postUser2(@ModelAttribute User user) { (1) users.put(user.getId(),user); return ImmutableMap.of("user",user); }

    (1) ModelAttribute 是Spring mvc的注解,这里Swagger可以解析这个注解,获得User的属性描述

    @ApiModel

    @ApiModel(value = "User", description = "用户对象") public class User { @ApiModelProperty(value = "ID") private Integer id; @ApiModelProperty(value = "姓名") private String name; @ApiModelProperty(value = "地址") private String address; @ApiModelProperty(value = "年龄",access = "hidden") private int age; @ApiModelProperty(value = "性别") private int sex; ....... }

    传递复杂对象 By RequestBody

    @ApiOperation(value="创建用户-传递复杂对象", notes="传递复杂对象DTO,json格式传递数据",produces = "application/json") @RequestMapping(value="/users-3", method= RequestMethod.POST) //json格式传递对象使用RequestBody注解 public User postUser3(@RequestBody User user) { users.put(user.getId(),user); return user; }

    PathVariable

    @ApiOperation(value="删除用户- PathVariable", notes="根据url的id来指定删除对象") @RequestMapping(value="/users/{id}", method = RequestMethod.DELETE) public void deleteUser(@PathVariable Integer id) { (1) users.remove(id); }

    (1) PathVariable是Spring 的注解,对于这种简单的参数,就可以不用写ApiParam来描述接口参数。

    数组的描述

    @ApiOperation(value="删除用户-传递数组", notes="删除对象,传递数组") @RequestMapping(value="/users/deleteByIds", method = RequestMethod.DELETE) public void deleteUser(@ApiParam("用户ID数组") @RequestParam Integer[] ids) { (1) for (int id:ids){ users.remove(id); } }

    (1) 这里用ApiParam为数组参数添加描述

    1.4 可选配置

    在application.properties中加入以下配置,用于设置测试请求的host,默认在swagger ui上做请求测试时都是以/users/1为路径发送请求。

    如果需要改变请求的根路径,就需要配置这个参数:

    springfox.documentation.swagger.v2.host = yourapp.abc.com

    配置获取api docs json数据的请求路径 ,默认为/v2/api-docs:

    springfox.documentation.swagger.v2.path = /api

    2. springfox-staticdocs 生成静态文档

    springfox

    2.1 Maven 配置

     

    1. <dependency>
    2. <groupId>io.springfoxgroupId>
    3. <artifactId>springfox-staticdocsartifactId>
    4. <version>2.2.2version>
    5. <scope>testscope>
    6. dependency>

    2.2 生成json文件

    编写Junit测试,这样在测试环节就可以将api-docs的json数据写入文档,便于下一步生成asciidoc文件。

     

    1. @WebAppConfiguration
    2. @RunWith(SpringJUnit4ClassRunner.class)
    3. @SpringBootTest(classes = DemoBootApplication.class)
    4. public class Swagger2MarkupTest {
    5. @Autowired
    6. private WebApplicationContext context;
    7. private MockMvc mockMvc;
    8. @Before
    9. public void setUp() {
    10. this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build();
    11. }
    12. @Test
    13. public void createSpringfoxSwaggerJson() throws Exception {
    14. String outputDir = "src/docs/json"; //将api-docs的json数据写入文件
    15. MvcResult mvcResult = this.mockMvc.perform(get("/v2/api-docs")
    16. .accept(MediaType.APPLICATION_JSON))
    17. .andExpect(status().isOk())
    18. .andReturn();
    19. MockHttpServletResponse response = mvcResult.getResponse();
    20. String swaggerJson = response.getContentAsString();
    21. Files.createDirectories(Paths.get(outputDir));
    22. try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputDir, "swagger.json"), StandardCharsets.UTF_8)) {
    23. writer.write(swaggerJson);
    24. }
    25. }
    26. }

    2.3 配置Maven Plugin

    配置以下两个插件:

    swagger2markup-maven-plugin,该插件将json文件转为asciidoc

    asciidoctor-maven-plugin, 该插件将asciidoc转为html/pdf

    执行Maven命令 : mvn swagger2markup:convertSwagger2markup process-resources

    生成的html文档存储在src\main\resources\META-INF\resources\docs目录下。

    启动DemoBootApplication,直接访问http://localhost:8080/docs/index.html。

    1. <pluginRepositories>
    2. <pluginRepository>
    3. <id>jcenter-snapshotsid>
    4. <name>jcentername>
    5. <url>http://oss.jfrog.org/artifactory/oss-snapshot-local/url>
    6. pluginRepository>
    7. <pluginRepository>
    8. <snapshots>
    9. <enabled>falseenabled>
    10. snapshots>
    11. <id>jcenter-releasesid>
    12. <name>jcentername>
    13. <url>http://jcenter.bintray.comurl>
    14. pluginRepository>
    15. pluginRepositories>
    16. <build>
    17. <plugins>
    18. <plugin>
    19. <groupId>io.github.swagger2markupgroupId>
    20. <artifactId>swagger2markup-maven-pluginartifactId>
    21. <version>${swagger2markup.plugin.version}version>
    22. <dependencies>
    23. <dependency>
    24. <groupId>io.github.swagger2markupgroupId>
    25. <artifactId>swagger2markup-import-files-extartifactId>
    26. <version>${swagger2markup.extension.version}version>
    27. dependency>
    28. <dependency>
    29. <groupId>io.github.swagger2markupgroupId>
    30. <artifactId>swagger2markupartifactId>
    31. <version>${swagger2markup.version}version>
    32. dependency>
    33. dependencies>
    34. <configuration>
    35. <swaggerInput>${swagger.input}swaggerInput>
    36. <outputDir>${generated.asciidoc.directory}outputDir>
    37. <config>
    38. <swagger2markup.markupLanguage>ASCIIDOCswagger2markup.markupLanguage>
    39. <swagger2markup.pathsGroupedBy>TAGSswagger2markup.pathsGroupedBy>
    40. config>
    41. configuration>
    42. <executions>
    43. <execution>
    44. <phase>generate-sourcesphase>
    45. <goals>
    46. <goal>convertSwagger2markupgoal>
    47. goals>
    48. execution>
    49. executions>
    50. plugin>
    51. <plugin>
    52. <groupId>org.asciidoctorgroupId>
    53. <artifactId>asciidoctor-maven-pluginartifactId>
    54. <version>1.5.3version>
    55. <dependencies>
    56. <dependency>
    57. <groupId>org.asciidoctorgroupId>
    58. <artifactId>asciidoctorj-pdfartifactId>
    59. <version>1.5.0-alpha.11version>
    60. dependency>
    61. <dependency>
    62. <groupId>org.jrubygroupId>
    63. <artifactId>jruby-completeartifactId>
    64. <version>${jruby.version}version>
    65. dependency>
    66. <dependency>
    67. <groupId>org.asciidoctorgroupId>
    68. <artifactId>asciidoctorjartifactId>
    69. <version>${asciidoctorj.version}version>
    70. dependency>
    71. dependencies>
    72. <configuration>
    73. <sourceDirectory>${asciidoctor.input.directory}sourceDirectory>
    74. <attributes>
    75. <doctype>bookdoctype>
    76. <toc>lefttoc>
    77. <toclevels>3toclevels>
    78. <numbered>numbered>
    79. <hardbreaks>hardbreaks>
    80. <sectlinks>sectlinks>
    81. <sectanchors>sectanchors>
    82. <generated>${generated.asciidoc.directory}generated>
    83. attributes>
    84. configuration>
    85. <executions>
    86. <execution>
    87. <id>output-htmlid>
    88. <phase>generate-resourcesphase>
    89. <goals>
    90. <goal>process-asciidocgoal>
    91. goals>
    92. <configuration>
    93. <backend>html5backend>
    94. <outputDirectory>${asciidoctor.html.output.directory}outputDirectory>
    95. configuration>
    96. execution>
    97. executions>
    98. plugin>
    99. plugins>
    100. build>


    3. 其他说明

    3.1 如何修改/v2/api-docs路径?

    swagger-ui是通过获取接口的json数据渲染页面的,即通过swagger的注解将生成接口的描述服务,默认地址为/v2/api-docs,如果需要改变这个请求地址,可以在properties中配置springfox.documentation.swagger.v2.path。

    3.2 如何设置所有请求的统一前缀?

    默认请求都是以 / 根路径开始,如果我们的应用不是部署在根路径,比如以/platform部署,则可以通过一下方式设置请求的统一前缀。

     

    1. @Bean
    2. public Docket createV1RestApi() {
    3. return new Docket(DocumentationType.SWAGGER_2)
    4. .apiInfo(apiInfo())
    5. .select()
    6. .apis(RequestHandlerSelectors.basePackage(SWAGGER_SCAN_BASE_PACKAGE))
    7. .paths(PathSelectors.any())
    8. .build()
    9. .pathMapping("/platform"); // 在这里可以设置请求的统一前缀
    10. }

    3.3 接口文档中1.4和1.5的信息生成

    接口文档中的 1.4和 1.5 则通过以下方式生成:

    1.4 URI scheme

    // 可以通过在properties中设置 springfox.documentation.swagger.v2.host属性

    Host : localhost

    // 待确认

    BasePath : /

    该Host也是swagger-ui发送测试请求的Host, 通常我们会将将接口文档部署在测试服务器,这样就需要设置Host,

    否则请求都是通过localhost发送,请求不到测试服务器的接口。

    1.5 Tags

    @Api(value = "/v1/users",tags = "Users",description = "用户接口V1")

    tags由Api注解的tags标签设置,如果不设置,则以类名作为tag

    3.4 设置响应对象的Example

    通过ApiModelProperty注解的example属性设置响应对象的示例:

     

    1. @ApiModelProperty(value = "ID",example = "1")
    2. private Integer id;
    3. @ApiModelProperty(value = "姓名",example = "Admin")
    4. private String name;
    5. @ApiModelProperty(value = "地址",example = "171")
    6. private String address;
    7. @ApiModelProperty(value = "年龄",access = "hidden",example = "20")
    8. private int age;
    9. @ApiModelProperty(value = "性别",example = "1")
    10. private int sex;
    11. @ApiModelProperty(value = "生日",example = "2000-10-22")

    其它:

    spring boot下建议使用:

    https://github.com/SpringForAll/spring-boot-starter-swagger

     

    1. <dependency>
    2. <groupId>com.spring4allgroupId>
    3. <artifactId>swagger-spring-boot-starterartifactId>
    4. <version>1.7.1.RELEASEversion>
    5. dependency>

    参考链接:

    springfox文档

    http://www.jianshu.com/p/b730b969b6a2

    Setting Up Swagger 2 with a Spring REST API | Baeldung 这个例子更合适由浅入深

    简单入门例子

    spring cloud 和 swagger的结合;

    Swagger2 – Piotr's TechBlog

  • 相关阅读:
    【AI视野·今日Sound 声学论文速览 第六期】Mon, 18 Sep 2023
    C# GetField 方法应用实例
    Python实战——Selenium与iframe结合应用
    断崖式难度春招,需要注意这些点
    webpack5 Image Minimizer减少图片体积提升打包构建速度
    系统管理员道德规范
    微服务实战 01 Nacos 入门
    AI发展历史
    Nginx动静分离、缓存配置、性能调优、集群配置
    抽空写了个小游戏(未完待续)
  • 原文地址:https://blog.csdn.net/luxideyao/article/details/134437057