Swagger快速上手

swagger官方文档:API Documentation & Design Tools for Teams | Swagger

(不管学习啥,读官方文档总没错)

什么是swagger

  •  号称世界上最流行的Api框架;
  • RestFul Api 文档在线自动生成工具,Api文档与API定义同步更新,实现边编写边实时更新,方便多人在线合作开发
  • 直接运行,可以在线测试API接口
  • 支持多种语言: (Java,Php....

现在我们基于springboot项目集成Swagger: 

新建一个springboot项目,基于maven,首先导入万能web依赖

 然后实现我们helloworld的controller接口,因为我们没有编写前端页面,就用RestController返回字符串进行环境测试。

package com.chenxi.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @RequestMapping("/hello")
    public String hello(){
        return "hello world";
    }

}

 

 成功访问,基本web环境没有问题,接下来引入swagger。

使用swagger所需依赖:(注意!使用最新3.0.0版本可能会访问swagger-ui.html报错!建议降版本至2.9.2)

  • swagger2
  • swagger-ui
<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>

如果使用2.9.3版本,一定要在springboot配置文件中添加:

spring.mvc.pathmatch.matching-strategy=ANT_PATH_MATCHER

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

 访问成功!

接下来配置我们的swagger

  •        Swagger的bean实例Docket;
    @Bean
    public Docket docket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo());
    }

 我们点进Docket源码可以看到:

 而DocumentationType中有三个属性可以选:

我们使用的是2.9.2版本。顾选择SWAGGER_2

  •         而我们还得创建一个返回ApiInfo的Bean实例,这部分是配置我们Swagger页面中Swagger信息部分的,并且翻遍源码,该类并未编写set方法,只可通过构造器注入值。

 

 @Bean
    public ApiInfo apiInfo(){
        Contact contact = new Contact("chenxi", "https://i.csdn.net/#/user-center/profile?spm=1000.2115.3001.5111", "785822438@qq.com");
        return new ApiInfo(
                "晨曦 Swagger Restful API",
                "代码和人一个能跑就行",
                "1.0",
                "https://luischen.com/",
                contact,
                "Swagger官网",
                "https://swagger.io/",
                new ArrayList()
        );

    }

 

这样基本的配置就完成啦!Swagger的使用体验还是要在具体项目中才能体验到哦! 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值