天天看点

SpringBoot 2.1.x整合Swagger2生成在线接口文档示例

  • 1、添加Swagger相关依赖
<dependencies>
  <!-- Swagger2 接口文档 -->
  <dependency>
      <groupId>com.spring4all</groupId>
      <artifactId>swagger-spring-boot-starter</artifactId>
      <version>1.9.1.RELEASE</version>
  </dependency>
  <!--美化API接口文档-->
  <dependency>
      <groupId>com.github.xiaoymin</groupId>
      <artifactId>swagger-bootstrap-ui</artifactId>
      <version>1.9.6</version>
  </dependency>

   <!--Lombok-->
   <dependency>
       <groupId>org.projectlombok</groupId>
       <artifactId>lombok</artifactId>
       <optional>true</optional>
   </dependency>
</dependencies>
           
  • 2、配置yaml参数
#端口设置
server:
  port: 9999
  servlet:
    context-path: /
spring:
  application:
    name: boot-swagger2
#开启swagger接口文档
swagger:
  enabled: true
           
  • 3、编写swagger配置文件
package com.hf.swagger2.confg;

import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;

/**
 * @Copyright (C), 2016-2020 HF
 * @ClassName: Swagger2Config
 * @Author: hf
 * @Date: 2020/12/11 16:08
 * @Description: Swagger2配置
 */
@EnableSwagger2
@Configuration
@ConditionalOnProperty(name = "enabled", prefix = "swagger", havingValue = "true", matchIfMissing = true)
public class Swagger2Config {


    @Value("${swagger.enabled:false}")
    private boolean enable;

    @Bean("HF API平台")
    public Docket docket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("HF API平台")
                .select()
                .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
                .paths(PathSelectors.regex("/sw.*"))
                .build()
                .apiInfo(apiInfo())
                .securitySchemes(securitySchemes())
                .enable(enable);
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .contact(new Contact("HF", "https://blog.csdn.net/weixin_44187730", "[email protected]"))
                .title("HF API接口文档")
                .description("HF 提供系统平台的详细Restful格式接口文档")
                .termsOfServiceUrl("http://127.0.0.1:9999/doc.html")
                .version("1.0.0")
                .build();
    }

    private List<ApiKey> securitySchemes() {
        List<ApiKey> apiKeyList = new ArrayList<>();
        apiKeyList.add(new ApiKey("Authorization", "Authorization", "header"));
        return apiKeyList;
    }
}

           
  • 4、Person实体
package com.hf.swagger2.entity;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Accessors;

/**
 * @Copyright (C), 2016-2019 hf
 * @FileName: Person
 * @Author: hf
 * @Date: 2019/12/11 10:30
 * @Description: Swagger2 测试Person实体类
 */

@Getter
@Setter
@ToString
@AllArgsConstructor
@Accessors(chain = true)
@ApiModel(value = "Person对象",description = "Swagger2测试实体类")
public class Person {

    @ApiModelProperty("人员主键标识")
    private Integer id;

    @ApiModelProperty("人员姓名")
    private String name;

    @ApiModelProperty("人员年龄")
    private Integer age;
}

           
  • 5、Swagger2Controller接口
package com.hf.swagger2.controller;

import com.hf.swagger2.entity.Person;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @Copyright (C), 2016-2019 hf
 * @FileName: Swagger2Controller
 * @Author: hf
 * @Date: 2019/12/11 10:37
 * @Description: Swagger2接口测试
 */
@Api(tags = "Swagger2接口Api测试")
@RestController
@RequestMapping("/sw")
public class Swagger2Controller {


    /**
     * 初始化人员信息
     */
    private static List<Person> perList;

    static {
        perList = new ArrayList<>();
        perList.add(new Person(1, "刘一", 20));
        perList.add(new Person(2, "陈二", 35));
        perList.add(new Person(3, "张三", 24));
        perList.add(new Person(4, "李四", 30));
        perList.add(new Person(5, "王五", 42));
    }

    @GetMapping("/findPerson/{name}/{age}")
    @ApiOperation(value = "根据人员名称和年龄查询人员信息", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "姓名", required = true, paramType = "path", dataType = "String"),
            @ApiImplicitParam(name = "age", value = "年龄", required = true, paramType = "path", dataType = "int")
    })
    public Object findPerson(@PathVariable String name, @PathVariable int age) {

        return perList.stream().filter(e -> ((e.getAge() > age) || (e.getName().equals(name)))).limit(2);
    }

    @GetMapping("/getName/{index}")
    @ApiOperation(value = "根据人员主键ID查询人员", httpMethod = "GET")
    @ApiImplicitParam(name = "index", value = "索引", required = true, paramType = "path", dataType = "int")
    public Person findOneByIndex(@PathVariable int index) {

        //1 防止索引越界
        index = index > perList.size() ? ((int) (Math.random() * perList.size())) : index;

        return perList.get(index);
    }

    @PostMapping("/savePerson")
    @ApiOperation(value = "添加人员", httpMethod = "POST")
    public List<Person> savePerson(@RequestBody Person person) {
        perList.add(person);
        return perList;
    }

}

           
  • 访问测试
    • 访问地址: http://127.0.0.1:9999/swagger-ui.html
      SpringBoot 2.1.x整合Swagger2生成在线接口文档示例
    • http://127.0.0.1:9999/doc.html
      SpringBoot 2.1.x整合Swagger2生成在线接口文档示例

继续阅读