swagger

作者: 请叫我的全名cv工程师 | 来源:发表于2020-03-14 19:35 被阅读0次

简介

Swagger是一款Restful接口的文档在线自动生成和功能测试功能软件。
Swagger是一个规范和完整的框架,用于生成、描述、调用和可视化Restful风格的Web服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步。

优缺点

优点
  节省了大量手写接口文档的时间
  通过注解自动生成在线文档
  接口在线调用调试

缺点
  代码耦合,需要注解支持
比较占内存
  无法测试错误的请求方式、参数及不限于这些

pom.xml 引用

<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>

开启注解 @EnableSwagger2

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Value("${swagger.enable}")
    private boolean swaggerEnable;
……
}

配置 docket

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Value("${swagger.enable}")
    private boolean swaggerEnable;

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(new ApiInfoBuilder()
                        //页面标题
                        .title("通知服务API")
                        //描述
                        .description("接口文档...,持续更新中")
                        //版本号
                        .version("9.0")
                        //创建人
                        .contact(new Contact("li", "https://www.jianshu.com/u/4e5bc4a73480", "598116345@qq.com"))
                        .license("The Apache License")
                        .licenseUrl("http://www.baidu.com")
                        .build())
                //分组
                .groupName("B")
                //是否开启 (true 开启  false隐藏。生产环境建议隐藏)
                .enable(swaggerEnable)
                .select()
                //控制暴露出去的路径下的实例
                //如果某个接口不想暴露,可以使用以下注解
                //@ApiIgnore 这样,该接口就不会暴露在 swagger2 的页面下
                .apis(RequestHandlerSelectors.basePackage("com.example.noticeservice.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    @Bean
    public Docket createRestApi2() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(new ApiInfoBuilder()
                        //页面标题
                        .title("通知服务API")
                        //描述
                        .description("接口文档...,持续更新中")
                        //版本号
                        .version("9.0")
                        //创建人
                        .contact(new Contact("li", "https://www.jianshu.com/u/4e5bc4a73480", "598116345@qq.com"))
                        .license("The Apache License")
                        .licenseUrl("http://www.baidu.com")
                        .build())
                //分组
                .groupName("A")
                //是否开启 (true 开启  false隐藏。生产环境建议隐藏)
                .enable(swaggerEnable)
                .select()
                //控制暴露出去的路径下的实例
                //如果某个接口不想暴露,可以使用以下注解
                //@ApiIgnore 这样,该接口就不会暴露在 swagger2 的页面下
                .apis(RequestHandlerSelectors.basePackage("com.example.noticeservice.controller"))
//                .paths(PathSelectors.any())
                .paths(PathSelectors.ant("/index"))
                .build();
    }
}
  • 可以配置多个docket ,结合groupName属性对接口进行分组,可以分开不同的开发人员开发的不同接口,或者按照一定的规则展示指定的接口。
  • 通过enable 属性进行设置是否启动swagger-ui 的文档,可以结合不同的环境进行配置,比如开发环境开启swagger-ui,生产环境隐藏,防止接口过分暴露。
  • api指定扫描包路径下的文件,path可以根据配置url路径来显示指定的url下的接口信息


    image.png

使用样例

接口类

@Api(tags = "邮件通知服务", value = "我是没啥用处的")
@RestController
@Validated
@RequestMapping("/mail")
public class MailController {
    private static final Logger LOGGER = LoggerFactory.getLogger(MailController.class);

    @Autowired
    private MailService mailService;

    @ApiOperation(value = "发送简单的邮件服务", notes = "simpleMail", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "string", name = "from", value = "发送者", defaultValue = "11111@qq.com", required = true),
            @ApiImplicitParam(dataType = "string", name = "to", value = "接受者", defaultValue = "598116345@qq.com", required = true),
            @ApiImplicitParam(dataType = "string", name = "subject", value = "邮件主题", defaultValue = "我是邮件主题", required = true),
            @ApiImplicitParam(dataType = "string", name = "mailText", value = "邮件内容", defaultValue = "我是邮件内容", required = true)
    })
    @RequestMapping("/simpleMail")
    public BaseResponse simpleMail(HttpServletRequest request,
                                   @NotEmpty @Email @RequestParam("from") String from,
                                   @NotEmpty @Email @RequestParam("to") String to,
                                   @NotEmpty @RequestParam("subject") String subject,
                                   @NotEmpty @RequestParam("mailText") String mailText) throws Exception {
        mailService.simpleMail(to, subject, mailText);
        return new SuccessResponse(request, String.format("发送给%s的邮件%s发送成功", to, subject));
    }
}

效果图


image.png

点击try it out 可以进行接口测试

image.png

对象类

@ApiModel
public class BaseResponse {
    @ApiModelProperty(value = "请求是否成功", dataType = "boolean")
    private boolean success;
    @ApiModelProperty(value = "返回信息", dataType = "String")
    private String message;
    @ApiModelProperty(value = "返回的状态码", dataType = "string")
    private String responseCode;
    @ApiModelProperty(value = "请求的url", dataType = "string")
    private String requestUrl;
    @ApiModelProperty(value = "请求的ip", dataType = "string")
    private String requestIp;
}

效果图


image.png

注解讲解

  • @Api

tags=“说明该类的作用,可以在UI界面上看到的注解”
value=“该参数没什么意义,在UI界面上也看到,所以不需要配置”

  • ApiIgnore 使用该注解忽略这个API,不会生成接口文档。可注解在类和方法上
  • @ApiOperation 用在方法上

value=“说明方法的用途、作用”
notes=“方法的备注说明”

  • @ApiImplicitParam:用来给方法入参增加说明

name:参数名
value:参数的汉字说明、解释
dataType: 参数类型,默认String
required : 参数是否必传,true必传
defaultValue:参数的默认值
paramType:参数放在哪个地方
header请求参数的获取:@RequestHeader,参数从请求头获取
query请求参数的获取:@RequestParam,参数从地址栏问号后面的参数获取
path(用于restful接口)请求参数的获取:@PathVariable,参数从URL地址上获取
body(不常用)参数从请求体中获取
form(不常用)参数从form表单中获取

  • @ApiImplicitParams:用在controller的方法上,一组@ApiImplicitParam

  • @ApiResponse:用在 @ApiResponses里边,一般用于表达一个错误的响应信息

code:数字,例如400
message:信息,例如"请求参数没填好"
response:抛出异常的类

  • @ApiResponses:用在controller的方法上,用于表示一组响应

  • @ApiModel:用在返回对象类上,描述一个Model的信息(这种一般用在post创建的时候,使用@RequestBody这样的场景,请求参数无法使用

  • @ApiImplicitParam注解进行描述的时候)

+@ApiModelProperty:用在出入参数对象的字段上,表示对model属性的说明或者数据操作更改

value = 字段说明
name = 重写属性名字
dataType = 重写属性类型
required = 是否必填,true必填
example = 举例说明
hidden = 隐藏

启动文档

输入项目根url +/swagger-ui.html 即可
例如
http://localhost:8001/noticeservice/swagger-ui.html

注意

  1. 如果controller方法没有使用特定的注解,比如@GetMapping,@PostMapping等注解,那么swagger-ui 会显示全部的方法。可以在使用@ApiOperation,指定显示对应的httpMethod,这样在显示swagger-ui 的时候就只会显示一种方法,但是真实情况是全部方法都可以使用。
 @ApiOperation(value = "发送简单的邮件服务", notes = "simpleMail", httpMethod = "GET")
 @RequestMapping("/simpleMail")

2.如果controller方法是@RequestParam 这种的,不是@RequestBody的,那么请补全@RequestParam的方法,否则Swagger在try it out的时候会默认为 application/json的格式,无法进行try it out 。 加上了@RequestParam 之后就会显示param的形式。

image.png

对比


image.png

3.如果是multipartFiles类型,暂时不要使用@ApiImplicitParam,使用了之后会当做普通的param类型来使用

参考资料

一小时掌握Swagger技术
SpringBoot整合Swagger2,再也不用维护接口文档了!
SpringBoot 集成 Swagger2(十一)
demo

相关文章

网友评论

      本文标题:swagger

      本文链接:https://www.haomeiwen.com/subject/pkxbdhtx.html