Swagger使用
一、简介
https://swagger.io/tools/swagger-ui/
Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步。
作用
- 接口的文档在线自动生成
- 功能测试
Swagger是一组开源项目,其中主要要项目如下
- Swagger-tools:提供各种与Swagger进行集成和交互的工具。例如模式检验、Swagger 1.2文档转换成Swagger 2.0文档等功能。
- Swagger-core: 用于Java/Scala的的Swagger实现。与JAX-RS(Jersey、Resteasy、CXF...)、Servlets和Play框架进行集成。
- Swagger-js: 用于JavaScript的Swagger实现。
- Swagger-node-express: Swagger模块,用于node.js的Express web应用框架。
- Swagger-ui:一个无依赖的HTML、JS和CSS集合,可以为Swagger兼容API动态生成优雅文档。
- Swagger-codegen:一个模板驱动引擎,通过分析用户Swagger资源声明以各种语言生成客户端代码
二、测试Demo
(1)创建项目
创建一个spring boot项目
(2)依赖
- <?xml version="1.0" encoding="UTF-8"?>
- <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <parent>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-parent</artifactId>
- <version>2.1.7.RELEASE</version>
- <relativePath/> <!-- lookup parent from repository -->
- </parent>
- <groupId>com.example</groupId>
- <artifactId>swagger</artifactId>
- <version>0.0.1-SNAPSHOT</version>
- <name>swagger</name>
- <description>Demo project for Spring Boot</description>
-
- <properties>
- <java.version>1.8</java.version>
- </properties>
-
- <dependencies>
- <!--Swagger依赖-->
- <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>
-
- <!--hibernate校验依赖 -->
- <dependency>
- <groupId>org.hibernate</groupId>
- <artifactId>hibernate-validator</artifactId>
- <version>6.0.16.Final</version>
- </dependency>
-
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
-
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-annotations</artifactId>
- <version>2.9.0</version>
- </dependency>
- </dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-maven-plugin</artifactId>
- </plugin>
- </plugins>
- </build>
-
- </project>
(3)application.properties配置
- #https://blog.csdn.net/z_k_h/article/details/81875828(为啥配置)
- logging.level.io.swagger.models.parameters.AbstractSerializableParameter=error
(4)Swagger2配置类
- package cn.zzq.config;
-
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.ComponentScan;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
- 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;
-
-
- @EnableSwagger2
- @ComponentScan(basePackages = {"cn.zzq.controller"})
- @Configuration
- public class SwaggerConfig implements WebMvcConfigurer {
- @Bean
- public Docket createRestApi() {
- return new Docket(DocumentationType.SWAGGER_2)
- .apiInfo(apiInfo())
- .select()
- .apis(RequestHandlerSelectors.any())
- .paths(PathSelectors.any())
- .build();
- }
- private ApiInfo apiInfo() {
- return new ApiInfoBuilder()
- .title("《SwaggerDemo的演示案例--》")//标题
- .description("description:项目摘要")//描述
- .termsOfServiceUrl("http://www.google.com.hk")//(不可见)条款地址,公司内部使用的话不需要配
- .contact(new Contact("Devil", "http://www.google.com.hk", "xx@qq.com"))//作者信息
- .version("2.9.2")//版本号
- .build();
- }
- }
如上代码所示,通过createRestApi函数创建Docket的Bean之后,apiInfo()用来创建该Api的基本信息(这些基本信息会展现在文档页面中)
(5)JsonResult
- package cn.zzq.bean;
-
-
- public class JsonResult {
-
- private String code;
-
- private String msg;
-
- private Object data;
-
- private int totalPage;
-
-
- public String getCode() {
- return code;
- }
-
- public void setCode(String code) {
- this.code = code;
- }
-
- public String getMsg() {
- return msg;
- }
-
- public void setMsg(String msg) {
- this.msg = msg;
- }
-
- public Object getData() {
- return data;
- }
-
- public void setData(Object data) {
- this.data = data;
- }
-
- public int getTotalPage() {
- return totalPage;
- }
-
- public void setTotalPage(int totalPage) {
- this.totalPage = totalPage;
- }
-
-
- public void success() {
- this.code = "200";
- this.msg = "请求成功!";
- }
-
- public void success(Object data) {
- success();
- this.data = data;
- }
-
- public void success(String msg) {
- success();
- this.msg = msg;
- }
-
- public void failure() {
- this.code = "500";
- this.msg = "请求失败!";
- }
-
- public void failure(String msg) {
- failure();
- this.msg = msg;
- }
-
- public void setFailure(Integer code, String msg) {
- this.code = code + "";
- this.msg = msg;
- }
- }
(6)User
- package cn.zzq.bean;
-
- import io.swagger.annotations.ApiModelProperty;
-
- import javax.validation.constraints.*;
-
- public class User {
- @ApiModelProperty(value="用户名")
- @NotEmpty(message="姓名不能为空")
- private String name;
-
- @ApiModelProperty(value="密码")
- @NotEmpty(message="密码不能为空")
- private String password;
-
- @ApiModelProperty(value="性别")
- @NotEmpty(message="性别不能为空")
- private String gender;
-
- @ApiModelProperty(value="年龄")
- @NotNull(message="年龄不能为空")
- @Min(value=18,message="必须年满18岁!")
- @Max(value=30,message="年龄不能大于30岁!")
- private Integer age;
-
- 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 getGender() {
- return gender;
- }
-
- public void setGender(String gender) {
- this.gender = gender;
- }
-
- public Integer getAge() {
- return age;
- }
-
- public void setAge(Integer age) {
- this.age = age;
- }
- }
(7)UserController
- package cn.zzq.controller;
-
- import cn.zzq.bean.JsonResult;
- import cn.zzq.bean.User;
- import io.swagger.annotations.*;
- import org.springframework.http.HttpStatus;
- import org.springframework.util.StringUtils;
- import org.springframework.validation.BindingResult;
- import org.springframework.validation.FieldError;
- import org.springframework.web.bind.annotation.*;
- import javax.validation.Valid;
- import java.util.ArrayList;
- import java.util.List;
-
- @Api(value="User的相关信息接口",description="User的相关信息接口", protocols="http")
- @RestController
- public class UserController {
-
- @ApiOperation(notes="获取所有user,无需参数",value="获取所有user", httpMethod = "GET")
- @GetMapping("/getAll")
- public Object getAll(){
- //查出的所有部门信息
- List<User> list = new ArrayList<User>();
- User user = new User();
- user.setAge(23);
- user.setGender("男");
- user.setName("zhangsan");
- user.setPassword("123456");
- list.add(user);
- return list;
- }
-
- @ApiOperation(value="获取单个user", notes="传入json格式",httpMethod = "POST")
- @PostMapping("/getOne")
- public Object getOne(@RequestBody @Valid User user, BindingResult result){
- JsonResult jsonResult = new JsonResult();
- if(result.hasErrors()){
- List<FieldError> fieldErrors = result.getFieldErrors();
- for(int i=0;i<fieldErrors.size();i++){
- //控制台打印不符合校验的字段名和错误提示
- System.out.println("error field is :"+fieldErrors.get(i).getField()+",message is :"+fieldErrors.get(i).getDefaultMessage());
- String errorMsg = fieldErrors.get(i).getDefaultMessage();
- if(!StringUtils.isEmpty(errorMsg)){
- jsonResult.setFailure(HttpStatus.BAD_REQUEST.value(),errorMsg);
- return jsonResult;
- }
- }
- }
- jsonResult.setFailure(HttpStatus.OK.value(),HttpStatus.OK.getReasonPhrase());
- return jsonResult;
- }
-
-
- @ApiOperation(value="根据名称获取user",notes="传入json格式")
- @ApiResponses({
- @ApiResponse(code = 200, message = "请求成功"),
- @ApiResponse(code = 500, message = "请求失败,后台服务出现异常"),
- @ApiResponse(code = 401, message = "代表此操作无权限访问"),
- @ApiResponse(code = 400, message = "表示请求参数错误"),
- })
- @PostMapping("/getOneByName")
- public Object getOneByName(@ApiParam(value = "用户名", required = true) @RequestBody String name){
- User u = new User();
- u.setAge(23);
- u.setGender("男");
- u.setName(name);
- u.setPassword("123456");
- return u;
- }
-
- @ApiOperation(value="修改用户",notes="参数非json格式", httpMethod="POST")
- @ApiImplicitParams({
- @ApiImplicitParam(paramType="query", name = "name", value = "用户名", required = true, dataType = "String"),
- @ApiImplicitParam(paramType="query", name = "possword", value = "密码", required = true, dataType = "String")
- })
- @PostMapping("/update")
- public Object update(String name,String possword){
- User u = new User();
- u.setAge(23);
- u.setGender("男");
- u.setName(name);
- u.setPassword(possword);
- return u;
- }
- }
(7)启动类
- package cn.zzq;
-
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- import springfox.documentation.swagger2.annotations.EnableSwagger2;
-
- @SpringBootApplication
- public class SwaggerApplication {
-
- public static void main(String[] args) {
- SpringApplication.run(SwaggerApplication.class, args);
- }
- }
(8)效果
http://localhost:8080/swagger-ui.html
三、Swagger使用的注解及其说明
@Api: 用在类上,说明该类的作用。
@ApiOperation:注解来给API增加方法说明。
@ApiImplicitParams : 用在方法上包含一组参数说明。
@ApiImplicitParam:用来注解来给方法入参增加说明。
@ApiResponses:用于表示一组响应
@ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息
l code:数字,例如400
l message:信息,例如"请求参数没填好"
l response:抛出异常的类
@ApiModel:描述一个Model的信息(一般用在请求参数无法使用@ApiImplicitParam注解进行描述的时候)
l @ApiModelProperty:描述一个model的属性
注意:@ApiImplicitParam的参数说明:
paramType:指定参数放在哪个地方 |
header:请求参数放置于Request Header,使用@RequestHeader获取
|