十分钟掌握Swagger

4 篇文章 0 订阅

Swagger

Swagger简介

  • 号称世界上最流行的Api框架
  • Restful Api文档在线自动生成工具,Api文档与Api定义同步更新
  • 直接运行,可以在线测试API接口
  • 支持多种语言

官网:https://swagger.io/
增强版:https://doc.xiaominfo.com/guide/useful.html#java%E5%BC%80%E5%8F%91
在项目中使用Swagger需要SpringBox:

  • swagger2
  • ui
    推荐一款正式项目常用的一款UI更好的swagger框架
    Knife4j

SpringBoot集成Swagger

  1. 新建一个web项目
  2. 导入相关依赖
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

<!-- 增强版配置 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.github.xiaoymin/swagger-bootstrap-ui -->
<dependency>
   <groupId>com.github.xiaoymin</groupId>
   <artifactId>swagger-bootstrap-ui</artifactId>
   <version>1.9.6</version>
</dependency>

<!--knife4j配置-->
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>knife4j-spring-boot-starter</artifactId>
            <version>2.0.8</version>
            <exclusions>
                <exclusion>
                    <groupId>io.swagger</groupId>
                    <artifactId>swagger-annotations</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

  1. 编写一个Hello Word工程

  2. 配置Swagger–>Config

    @Configuration
    @EnableSwagger2         //开启swagger
    public class SwaggerConfig {
        
    }
    
  3. 测试运行

    在这里插入图片描述
    增强版
    在这里插入图片描述
    knife4j
    在这里插入图片描述

配置Swagger增强版

Swagger的bean实例Docket

观看源码我们可以找到相对应的配置参数,覆盖掉原来的默认参数

@Configuration
@EnableSwagger2
@EnableSwaggerBootstrapUI
public class SwaggerConfig {

    @Bean
    public Docket docket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //RequestHandlerSelectors==>配置扫描接口的方式
                //basePackage:指定扫描的包
                //any():扫描全部
                //none():不扫描
                //withClassAnnotation():扫描类上的注解
                //withMethodAnnotation():扫描方法上的注解
                .apis(RequestHandlerSelectors.basePackage("com.ze.eduservice.controller"))
                /**
                 * 过滤什么路径
                 */
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("swagger-bootstrap-ui RESTful APIs")
                .description("swagger-bootstrap-ui")
                .termsOfServiceUrl("https://blog.csdn.net/qq_42295733")
                .contact("lizeyu955@gmail.com")
                .version("1.0")
                .build();
    }
}

配置knife4j

@Configuration
@EnableSwagger2WebMvc
public class SwaggerConfig {

    @Autowired
    private MyProperties properties;

    @Bean
    public Docket docket(Environment environment){
        //设置要显示的swagger环境
        Profiles profiles = Profiles.of("dev","test");
        //判断是否在环境中
        boolean flag = environment.acceptsProfiles(profiles);
        SwaggerProperties swagger = properties.getSwagger();
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo(swagger))
                .enable(flag)
                .select()
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                //过滤什么路径
                .paths(PathSelectors.any())
                .build()
                /* 设置安全模式,swagger可以设置访问token */
                .securitySchemes(securitySchemes())
                .securityContexts(securityContexts());

    }


    /**
     * 安全模式,这里指定token通过Authorization头请求头传递
     */
    private List<ApiKey> securitySchemes()
    {
        List<ApiKey> apiKeyList = new ArrayList<ApiKey>();
        apiKeyList.add(new ApiKey("Authorization", "Authorization", "header"));
        return apiKeyList;
    }

    /**
     * 安全上下文
     */
    private List<SecurityContext> securityContexts()
    {
        List<SecurityContext> securityContexts = new ArrayList<>();
        securityContexts.add(
                SecurityContext.builder()
                        .securityReferences(defaultAuth())
                        .forPaths(PathSelectors.regex("^(?!auth).*$"))
                        .build());
        return securityContexts;
    }

    /**
     * 默认的安全上引用
     */
    private List<SecurityReference> defaultAuth()
    {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        List<SecurityReference> securityReferences = new ArrayList<>();
        securityReferences.add(new SecurityReference("Authorization", authorizationScopes));
        return securityReferences;
    }


    //配置Swagger信息
    private ApiInfo apiInfo(SwaggerProperties swagger) {
        return new ApiInfo(
                swagger.getTitle(),
                swagger.getDescription(),
                swagger.getVersion(),
                null,
                new Contact(swagger.getAuthor(), swagger.getUrl(), swagger.getEmail()),
                swagger.getLicense(), swagger.getLicenseUrl(), Collections.emptyList());
    }
}

@Data
@Component
@Configuration
@ConfigurationProperties(prefix = "ze")
public class MyProperties {

    private boolean openAopLog = true;

    private SwaggerProperties swagger = new SwaggerProperties();
}

/**
 * @author lizeyu
 */
@Data
public class SwaggerProperties {
    private String basePackage;
    private String title;
    private String description;
    private String version;
    private String author;
    private String url;
    private String email;
    private String license;
    private String licenseUrl;
}

配置Swagger文档分组

.groupName("南风")

在这里插入图片描述

配置多个分组只需配置多个Docket()即可

实体类配置

@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("edu_teacher")
@ApiModel(value="Teacher对象", description="讲师")
public class Teacher implements Serializable {

    private static final long serialVersionUID = 1L;

    @ApiModelProperty(value = "讲师ID")
    private String id;

    @ApiModelProperty(value = "讲师姓名")
    private String name;

    @ApiModelProperty(value = "讲师简介")
    private String intro;

    @ApiModelProperty(value = "讲师资历,一句话说明讲师")
    private String career;

    @ApiModelProperty(value = "头衔 1高级讲师 2首席讲师")
    private Integer level;

    @ApiModelProperty(value = "讲师头像")
    private String avatar;

    @ApiModelProperty(value = "排序")
    private Integer sort;

    @ApiModelProperty(value = "乐观锁")
    @Version
    private Integer version;

    @ApiModelProperty(value = "逻辑删除")
    @TableLogic
    private Integer isDeleted;

    @ApiModelProperty(value = "创建时间")
    @TableField(fill = FieldFill.INSERT)
    private LocalDateTime createTime;

    @ApiModelProperty(value = "修改时间")
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private LocalDateTime updateTime;


}

接口Controller配置标签

定义在类上:@Api
定义在方法上:@ApiOperation
定义在参数上:@ApiParam

@Api(tags = "教师相关接口",description = "教师信息的管理")
@RestController
@RequestMapping("/eduservice/teacher")
public class TeacherController {

    @Autowired
    private TeacherService service;

    /**
     * 查询讲师表所有数据
     */
    @ApiOperation(value = "查询所有教师",notes = "无参数")
    @GetMapping("/findAll")
    public R findAll() {
        return R.data(service.findAll());
    }


    /**
     * 删除教师
     */
    @ApiOperation(value = "删除一条数据", notes = "提供教师Id")
    @DeleteMapping("/remove/{id}")
    public R remove(@PathVariable Integer id) {
        return R.status(service.delete(id));
    }

}

总结:

  1. 我们可以通过Swagger给一些比较难理解的属性或接口,增加注释信息
  2. 接口文档实时更新
  3. 可以在线测试
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

nan feng

打赏一杯咖啡吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值