IT学习笔记--Swagger2(API在线文档)

1. Swagger2的作用

由于Spring Boot能够快速开发、便捷部署等特性,相信有很大一部分Spring Boot的用户会用来构建RESTful API。而我们构建RESTful API的目的通常都是由于多终端的原因,这些终端会共用很多底层业务逻辑,因此我们会抽象出这样一层来同时服务于多个移动端或者Web前端。

这样一来,我们的RESTful API就有可能要面对多个开发人员或多个开发团队:IOS开发、Android开发或是Web开发等。为了减少与其他团队平时开发期间的频繁沟通成本,传统做法我们会创建一份RESTful API文档来记录所有接口细节,然而这样的做法有以下几个问题:

  • 由于接口众多,并且细节复杂(需要考虑不同的HTTP请求类型、HTTP头部信息、HTTP请求内容等),高质量地创建这份文档本身就是件非常吃力的事,下游的抱怨声不绝于耳。
  • 随着时间推移,不断修改接口实现的时候都必须同步修改接口文档,而文档与代码又处于两个不同的媒介,除非有严格的管理机制,不然很容易导致不一致现象。

为了解决上面这样的问题,本文将介绍RESTful API的重磅好伙伴Swagger2,它可以轻松的整合到Spring Boot中,并与Spring MVC程序配合组织出强大RESTful API文档。它既可以减少我们创建文档的工作量,同时说明内容又整合入实现代码中,让维护文档和修改代码整合为一体,可以让我们在修改代码逻辑的同时方便的修改文档说明。另外Swagger2也提供了强大的页面测试功能来调试每个RESTful API。

2. 使用Swagger2需要的依赖包

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

其中:

  • springfox-swagger2 用于JSON API文档的生成;
  • springfox-swagger-ui 用于文档界面展示。

3. Swagger2配置

package com.example.springbootdemo.config;

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.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * 在线API文档配置
 * @author xudasong
 */
@EnableSwagger2
@Configuration
public class SwaggerConfiguration {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.springbootdemo"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("springboot利用swagger构建api文档")
                .description("简单优雅的restfun风格,http://blog.csdn.net/saytime")
                .termsOfServiceUrl("http://blog.csdn.net/saytime")
                .version("1.0")
                .build();
    }

}

4. Swagger2应用

package com.example.springbootdemo.controller;

import com.example.springbootdemo.mapper.UserMapper;
import com.example.springbootdemo.model.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@Api(tags = "Hello控制器服务")
@RestController
public class HelloController {

   @Autowired
    private UserMapper userMapper;

   @ApiOperation(value = "hello方法", notes = "hello方法")
    @RequestMapping(value = "/hello",method = RequestMethod.GET)
    private String index(){
        return "Hello World!";
    }

    @ApiOperation(value = "登录", notes = "根据用户id查询用户信息")
    @ApiImplicitParam(name = "id",value = "用户id",required = true, dataType = "String",paramType = "path")
    @RequestMapping(value = "/login/{id}",method = RequestMethod.GET)
    private String login(@PathVariable(value = "id") String id){
        User user = userMapper.findUserById(id);
        return "userName: " + user.getUsername() + " userId: "+user.getId();
    }
}

访问localhost:8088/swagger-ui.html效果如下:

5. Swagger2 相关注解详情

(1)@Api:用在请求的类上,表示对类的说明
            tags="说明该类的作用,可以在UI界面上看到的注解"
            value="该参数没什么意义,在UI界面上也看到,所以不需要配置"

(2)@ApiOperation:用在请求的方法上,说明方法的用途、作用
             value="说明方法的用途、作用"
             notes="方法的备注说明"

(3)@ApiImplicitParams:用在请求的方法上,表示一组参数说明
             @ApiImplicitParam:用在@ApiImplicitParams注解中,指定一个请求参数的各个方面
                name:参数名
                value:参数的汉字说明、解释
                required:参数是否必须传
                paramType:参数放在哪个地方
                 · header --> 请求参数的获取:@RequestHeader
                 · query --> 请求参数的获取:@RequestParam
                 · path(用于restful接口)--> 请求参数的获取:@PathVariable
                 · body(不常用)
                 · form(不常用)       
             dataType:参数类型,默认String,其它值dataType="Integer"       
             defaultValue:参数的默认值

如:

@ApiImplicitParams({
	@ApiImplicitParam(name="mobile",value="手机号",required=true,paramType="form"),
	@ApiImplicitParam(name="password",value="密码",required=true,paramType="form"),
	@ApiImplicitParam(name="age",value="年龄",required=true,paramType="form",dataType="Integer")
})

 (4)@ApiResponses:用在请求的方法上,表示一组响应
              @ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息
               code:数字,例如400
               message:信息,例如"请求参数没填好"
               response:抛出异常的类

如:

@ApiOperation(value = "select1请求",notes = "多个参数,多种的查询参数类型")
@ApiResponses({
	@ApiResponse(code=400,message="请求参数没填好"),
	@ApiResponse(code=404,message="请求路径没有或页面跳转路径不对")
})

(5)@ApiModel:用于响应类上,表示一个返回响应数据的信息
            (这种一般用在post创建的时候,使用@RequestBody这样的场景,
            请求参数无法使用@ApiImplicitParam注解进行描述的时候)

(6)@ApiModelProperty:用在属性上,描述响应类的属性
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值