swagger2注解-使用手册-2.7.0

一、swagger2概述

现如今,前后端分离已经逐渐成为互联网项目一种标准的开发方式,前端与后端交给不同的人员开发。项目开发中的沟通成本随之升高,这部分沟通成本主要在于前端开发人员与后端开发人员对WebAPI接口的沟通。

手写Api文档的几个痛点: 文档需要更新的时候,需要再次发送一份给前端,也就是文档更新交流不及时。 接口返回结果不明确,不能直接在线测试接口,通常需要使用工具,比如postman 接口文档太多,不好管理。

Swagger2 就可以很好地解决,通过一些配置,它可以动态生成Api接口文档,降低沟通成本,促进项目高效开发。

当然也不能说Swagger就一定是完美的,当然也有缺点,最明显的就是代码移入性比较强。

二、swagger2常用注解

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

2.@ApiOperation:用在请求的方法上,说明方法的用途、作用
value:说明方法的用途,作用(此说明再xxx-controller下,点击才能看到)
notes:方法的备用说明 (当有此值时:该接口说明会到页面中的主界面上)
tags:此参数不应该用到方法上,不然会在首页中独立展示为一个接口,这个接口与存在在controller文件中的接口描述相同,冗余

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注解进行描述的时候)
◆示例:

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

import java.io.Serializable;

@ApiModel(description= "返回响应数据")
public class RestMessage implements Serializable{

    @ApiModelProperty(value = "是否成功")
    private boolean success=true;
    @ApiModelProperty(value = "返回对象")
    private Object data;
    @ApiModelProperty(value = "错误编号")
    private Integer errCode;
    @ApiModelProperty(value = "错误信息")
    private String message;

    /* getter/setter */
}

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

7.@ApiIgnore 忽视方法(不在UI界面上展示这个方法)

三、swagger2依赖

CBB项目中,选择用springboot 集成swagger2,当前最新的swagger2版本应该是2.9.2,考虑展示效果,目前项目选择使用2.7.0版本。
◆ pom文件添加如下依赖:


	io.springfox
	springfox-swagger2
	2.7.0



	io.springfox
	springfox-swagger-ui
	2.7.0

四、Swagger2配置类

其实这个配置类,只要了解具体能配置哪些东西就好了,毕竟这个东西配置一次之后就不用再动了。 特别要注意的是里面配置了api文件也就是controller包的路径,不然生成的文档扫描不到接口。

package com.fager.swagger2;

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;

/**
 * @author fager
 * @ClassName run.com.cbb.Swgger2
 * @Description
 * @date 2019-08-27 22:12:31
 */
@Configuration
public class Swagger2 {

	@Bean
	public Docket createRestApi() {
		return new Docket(DocumentationType.SWAGGER_2)
				.apiInfo(apiInfo())
				.select()
				.apis(RequestHandlerSelectors.basePackage("run.com.cbb"))
				.paths(PathSelectors.any())
				.build();
	}
	
	private ApiInfo apiInfo() {
		return new ApiInfoBuilder()
				.title("springboot利用swagger构建api文档")
				.description("简单优雅的restful风格!")
				.termsOfServiceUrl("")
				.version("1.0")
				.build();
	}
}

◆ 用@Configuration注解该类,等价于XML中配置beans;用@Bean标注方法等价于XML中配置bean。

◆ Application.class 加上注解@EnableSwagger2 表示开启Swagger

package run.com.cbb;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@SpringBootApplication
@EnableSwagger2
public class SpringbootSwagger2Application {

	public static void main(String[] args) {
		SpringApplication.run(SpringbootSwagger2Application.class, args);
	}
}

五、Restful接口示例

  1. 实体User.class文件
package com.fager.swagger2.entity;

import io.swagger.annotations.ApiModelProperty;
import java.util.Date;

/**
 * @ClassName User
 * @Description TODO
 * @Author fager
 * @Date 2019/8/28 0028 19:29
 * @Version 1.0
 */
public class User {

    @ApiModelProperty(value = "用户id",required = true,example = "123")
    private int id;

    @ApiModelProperty(value = "用户名",required = true,example = "zhangsan")
    private String username;

    @ApiModelProperty(value = "用户年龄",required = true,example = "23")
    private int age;

    @ApiModelProperty(value = "用户出生日期",required = true,example = "2008-08-28T12:27:02.517Z")
    private Date ctm;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Date getCtm() {
        return ctm;
    }

    public void setCtm(Date ctm) {
        this.ctm = ctm;
    }
}

2.Json格式输出类 JsonResult.class文件

package com.fager.swagger2.entity;

/**
 * @ClassName JsonResult
 * @Description TODO
 * @Author fager
 * @Date 2019/8/28 0028 19:30
 * @Version 1.0
 */
public class JsonResult {

    private String status = null;
    private Object result = null;

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public Object getResult() {
        return result;
    }

    public void setResult(Object result) {
        this.result = result;
    }
}

3.控制层 UserController.class文件

package com.fager.swagger2.controller;

import com.fager.swagger2.entity.JsonResult;
import com.fager.swagger2.entity.User;
import com.fager.swagger2.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

/**
 * @ClassName UserController
 * @Description TODO
 * @Author fager
 * @Date 2019/8/28 0028 19:31
 * @Version 1.0
 */
@RestController
@Api(value = "",tags = "用户操作接口")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 根据ID查询用户
     * @param id
     * @return
     */
    @ApiOperation(value="获取用户详细信息", notes="根据url的id来获取用户详细信息")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Integer", paramType = "path",defaultValue = "0")
    @RequestMapping(value = "user/{id}", method = RequestMethod.GET)
    public ResponseEntity getUserById (@PathVariable(value = "id") Integer id){
        return userService.getUserById(id);
    }

    /**
     * 查询用户列表
     * @return
     */
    @ApiOperation(value="获取用户列表", notes="获取用户列表")
    @RequestMapping(value = "users", method = RequestMethod.GET)
    public ResponseEntity getUserList (){
        return userService.getUserList();
    }

    /**
     * 添加用户
     * @param user
     * @return
     */
    @ApiOperation(value="创建用户", notes="根据User对象创建用户")
    @ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")
    @RequestMapping(value = "user", method = RequestMethod.POST)
    public ResponseEntity add (@RequestBody User user){

        return userService.add(user);
    }

    /**
     * 根据id删除用户
     * @param id
     * @return
     */
    @ApiOperation(value="删除用户", notes="根据url的id来指定删除用户")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long", paramType = "path")
    @RequestMapping(value = "user/{id}", method = RequestMethod.DELETE)
    public ResponseEntity delete (@PathVariable(value = "id") Integer id){
        return userService.delete(id);
    }

    /**
     * 根据id修改用户信息
     * @param user
     * @return
     */
    @ApiOperation(value="更新信息", notes="根据url的id来指定更新用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long",paramType = "path"),
            @ApiImplicitParam(name = "user", value = "用户实体user", required = true, dataType = "User")
    })
    @RequestMapping(value = "user/{id}", method = RequestMethod.PUT)
    public ResponseEntity update (@PathVariable("id") Integer id, @RequestBody User user){
        return userService.update(id,user);
    }

    @ApiIgnore//使用该注解忽略这个API
    @RequestMapping(value = "/hi", method = RequestMethod.GET)
    public String  jsonTest() {
        return " hi you!";
    }
}

4.业务层 UserService层 UserService.class文件

package com.fager.swagger2.service;

import com.fager.swagger2.entity.Student;

import java.util.List;

/**
 * @Author fager
 * @Date 2019/8/27 0027
 * @Description TODO
 */
public interface StudentService {
    public List queryAll();
    public Student queryOneById(String id);
    public void addOne(Student student);
    public void update(Student student);
    public void deleteOne(String id);
}

5.业务层实现类 UserServiceImpl.class文件

package com.fager.swagger2.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.fager.swagger2.entity.JsonResult;
import com.fager.swagger2.entity.User;
import com.fager.swagger2.service.UserService;
import org.springframework.http.ResponseEntity;

import java.util.*;

/**
 * @ClassName UserServiceImpl
 * @Description TODO
 * @Author fager
 * @Date 2019/8/28 0028 22:27
 * @Version 1.0
 */
public class UserServiceImpl implements UserService {
    // 创建线程安全的Map
    static Map users = Collections.synchronizedMap(new HashMap());

    public ResponseEntity getUserById(Integer id) {
        JsonResult r = new JsonResult();
        try {
            User user = users.get(id);
            r.setResult(user);
            r.setStatus("ok");
        } catch (Exception e) {
            r.setResult(e.getClass().getName() + ":" + e.getMessage());
            r.setStatus("error");
            e.printStackTrace();
        }
        return ResponseEntity.ok(r);
    }

    public ResponseEntity getUserList() {
        JsonResult r = new JsonResult();
        try {
            List userList = new ArrayList(users.values());
            r.setResult(userList);
            r.setStatus("ok");
        } catch (Exception e) {
            r.setResult(e.getClass().getName() + ":" + e.getMessage());
            r.setStatus("error");
            e.printStackTrace();
        }
        return ResponseEntity.ok(r);
    }

    public ResponseEntity add(User user) {
        JsonResult r = new JsonResult();
        try {
            users.put(user.getId(), user);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("user",user);
            r.setResult(jsonObject);
            r.setStatus("ok");
        } catch (Exception e) {
            r.setResult(e.getClass().getName() + ":" + e.getMessage());
            r.setStatus("error");

            e.printStackTrace();
        }
        return ResponseEntity.ok(r);
    }

    public ResponseEntity delete(Integer id) {
        JsonResult r = new JsonResult();
        try {
            users.remove(id);
            r.setResult(id);
            r.setStatus("ok");
        } catch (Exception e) {
            r.setResult(e.getClass().getName() + ":" + e.getMessage());
            r.setStatus("error");

            e.printStackTrace();
        }
        return ResponseEntity.ok(r);
    }

    public ResponseEntity update(Integer id, User user) {
        JsonResult r = new JsonResult();
        try {
            User u = users.get(id);
            u.setUsername(user.getUsername());
            u.setAge(user.getAge());
            users.put(id, u);
            r.setResult(u);
            r.setStatus("ok");
        } catch (Exception e) {
            r.setResult(e.getClass().getName() + ":" + e.getMessage());
            r.setStatus("error");

            e.printStackTrace();
        }
        return ResponseEntity.ok(r);
    }
}

6.启动配置类 Swagger2Application.class文件

package com.fager.swagger2;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
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.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@SpringBootApplication
@EnableSwagger2
@Configuration
public class Swagger2Application {
    public static void main(String[] args) {
        SpringApplication.run(Swagger2Application.class,args);
    }

    @Bean
    public Docket controllerApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(new ApiInfoBuilder()
                        .title("CBB Restful APIs")
                        .description("CBB-项目")
                        .termsOfServiceUrl("")
                        .version("2019.08.27")
                        .contact("通用应用部")
                        .build())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.fager.swagger2.controller"))
                .paths(PathSelectors.any())
                .build();
    }
}

你可能感兴趣的:(学习笔记)