Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步。Swagger 让部署管理和使用功能强大的API从未如此简单。
一、添加依赖:
io.springfox
springfox-swagger-ui
2.7.0
io.springfox
springfox-swagger2
2.7.0
二、创建SwaggerConfig配置类
方式一:
package com.spring.bootdemo.swagger.config;
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket swaggerSpringMvcPlugin() {
//select():选择那些路径和 api 会生成 document。此处设置为使用ApiOperation注解的接口。会生成接口文档
return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)).build();
}
}
方式二:
package com.spring.bootdemo.swagger.config;
import io.swagger.annotations.ApiOperation;
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.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket accessToken2() {
return new Docket(DocumentationType.SWAGGER_2).groupName("所有接口")// 定义组
.select() // 选择那些路径和 api 会生成 document
.apis(RequestHandlerSelectors.basePackage("com.spring.bootdemo.controller")) // 拦截的包路径
//.paths(PathSelectors.regex("/user/.*"))// 拦截的接口路径
.paths(PathSelectors.any()) //拦截所有接口
.build() // 创建
.apiInfo(apiInfo()); // 配置说明
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("BootDemo项目接口文档")// 标题
.description("个人博客项目")// 描述
.contact(new Contact("林建皓", "http://www.baidu.com","[email protected]"))// 联系
//.termsOfServiceUrl("http://www.roncoo.com") //服务条款的URL
// .license("Apache License Version 2.0")// 开源协议
// .licenseUrl("https://github.com/springfox/springfox/blob/master/LICENSE")//地址
.version("1.0")// 版本
.build();
}
}
三、创建配置User、R(restful风格统一返回对象)、Controller
package cn.itboot.system.entity;
import java.io.Serializable;
/**
* @ClassName User
* @Author linjianhao
* @Date 2019/2/12 16:47
* @Version 1.0
**/
public class User implements Serializable {
private static final long serialVersionUID = -5189662363457482440L;
private String userId;
private String name;
private String passWord;
private String email;
private String address;
private String images;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getImages() {
return images;
}
public void setImages(String images) {
this.images = images;
}
public User(String userId, String name, String passWord, String email) {
this.userId = userId;
this.name = name;
this.passWord = passWord;
this.email = email;
}
}
package cn.itboot.common.utils;
import java.util.HashMap;
import java.util.Map;
public class R extends HashMap {
private static final long serialVersionUID = 1L;
public R() {
put("code", 0);
put("msg", "操作成功");
}
public static R error() {
return error(1, "操作失败");
}
public static R error(String msg) {
return error(500, msg);
}
public static R error(int code, String msg) {
R r = new R();
r.put("code", code);
r.put("msg", msg);
return r;
}
public static R ok(String msg) {
R r = new R();
r.put("msg", msg);
return r;
}
public static R ok(int code,String msg) {
R r = new R();
r.put("code", code);
r.put("msg", msg);
return r;
}
public static R ok(Map map) {
R r = new R();
r.putAll(map);
return r;
}
public static R ok() {
return new R();
}
@Override
public R put(String key, Object value) {
super.put(key, value);
return this;
}
}
package com.spring.bootdemo.controller;
import com.spring.bootdemo.common.util.R;
import com.spring.bootdemo.swagger.bean.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
@Api(description = "用户接口")
@RestController
@RequestMapping(value = "/sys")
public class DemoController {
@ApiOperation(value = "新增用户",notes = "新增注册")
@RequestMapping(value = "createUser",method = RequestMethod.POST,consumes = MediaType.APPLICATION_JSON_VALUE)
public R createUser(@RequestBody User user){
System.out.println("createUser:::"+user.toString());
return R.ok(HttpStatus.OK.value(),"新增成功");
}
@ApiOperation(value = "修改用户" , notes="修改用户")
@RequestMapping(value="/updateUser",method=RequestMethod.POST,consumes= MediaType.APPLICATION_JSON_VALUE)
public R updateUser(@RequestBody User user){
System.out.println("updateUser:::"+user.toString());
return R.ok(HttpStatus.OK.value(), "修改成功.");
}
@ApiOperation(value = "删除用户" , notes="删除用户")
@ApiImplicitParams({
@ApiImplicitParam(name = "userId", value = "用户标识", required = true, paramType = "query", dataType = "String")
})
@RequestMapping(value="/deleteUser",method=RequestMethod.DELETE)
public R deleteUser(@RequestParam("userId") String userId){
System.out.println("deleteUser:::"+userId);
return R.ok(HttpStatus.OK.value(), "删除成功.");
}
@ApiOperation(value = "查询用户" , notes="查询用户")
@ApiImplicitParams({
@ApiImplicitParam(name = "userId", value = "用户标识", required = true, paramType = "query", dataType = "String")
})
@RequestMapping(value="/queryUser",method=RequestMethod.GET)
public R queryUser(@RequestParam("userId") String userId){
System.out.println("queryUser:::"+userId);
User user = new User(userId, "张三", "******", "[email protected]");
return R.ok(HttpStatus.OK.value(), "张三");
}
}
访问:http://localhost:8080/swagger-ui.html
注解解释:
@Api(description = "Controller描述"):用于类,修饰整个类,描述Controller的作用
@ApiOperation(value = "新增用户",notes = "新增注册"):用于方法,表示一个http请求的操作
@ApiParam()用于方法,参数,字段说明; 表示对参数的添加元数据(说明或是否必填等) ,
@ApiModel()用于类,表示对类进行说明,用于参数用实体类接收
@ApiModelProperty()用于方法,字段,表示对model属性的说明或者数据操作更改
@ApiIgnore()用于类,方法,方法参数,表示这个方法或者类被忽略
@ApiImplicitParam() 用于方法,表示单独的请求参数
@ApiImplicitParams() 用于方法,包含多个 @ApiImplicitParam
附注:
常用的5个注解
@Api:修饰整个类,描述Controller的作用
@ApiOperation:描述一个类的一个方法,或者说一个接口
@ApiParam:单个参数描述
@ApiModel:用对象来接收参数
@ApiProperty:用对象接收参数时,描述对象的一个字段
其它注解
@ApiResponse:HTTP响应其中1个描述
@ApiResponses:HTTP响应整体描述
@ApiIgnore:使用该注解忽略这个API
@ApiClass
@ApiError :发生错误返回的信息
@ApiErrors
@ApiParamImplicitL:一个请求参数
@ApiParamsImplicit 多个请求参数