swagger integration

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

To use swagger, we must configure swagger. We need to create a swagger configuration class, for example, it can be named
SwaggerConfig.java

package com.example.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.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/*
* 用于配置SwaggerApi
* */
//开启Swagger使用(项目注释文档)
@EnableSwagger2
//标明是配置类
@Configuration
public class SwaggerConfig {
    
    
 
    @Bean
    public Docket createRestApi() {
    
    
        return new Docket(DocumentationType.SWAGGER_2)
                //用于生成API信息
                .apiInfo(apiInfo())
                //select()函数返回一个ApiSelectorBuilder实例,用来控制接口被swagger做成文档
                .select()
                //用于指定扫描哪个包下的接口
                .apis(RequestHandlerSelectors.basePackage("com.example.controller"))
                //选择所有的API,如果你想只为部分API生成文档,可以配置这里
                .paths(PathSelectors.any()) 
                .build();
    }
 
    /*
     *用于定义API主界面的信息,比如可以声明所有的API的总标题、描述、版本
     */
    private ApiInfo apiInfo() {
    
    
        return new ApiInfoBuilder()
                //用来自定义API的标题
                .title("Hello SwaggerAPI")
                //用来描述整体的API
                .description("我想在这里描述点啥,但是又不知道说些什么?")
                //创建人信息
                .contact(new Contact("lixp","http://localhost:8082/swagger-ui.html","[email protected]"))
                //用于定义服务的域名
                //.termsOfServiceUrl("")
                .version("1.0") //可以用来定义版本
                .build();
    }
}

Configuration file addition (both SpringBoot2.5 and above need to be added)

spring:
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher

Run our Spring Boot project, (my port 8080 is occupied, if you are different, please pay attention to modify the subsequent url),
visit http://localhost:8082/swagger-ui.html
and you can see a In the following interface, since we have not configured the interface data for the time being, the following shows No operations defined
in spec!

define group interface

After using @Api to mark a Controller, if there is an interface below, the document will be generated by default, but there is no custom description
:

package com.its.swagger.controller;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@Api(tags = "用户管理")
@RestController
public class UserController {
    
    
// 注意,对于swagger,不要使用@RequestMapping,
// 因为@RequestMapping支持任意请求方式,swagger会为这个接口生成7种请求方式的接口文档
@GetMapping("/info")
public String info(String id){
    
    
return "aaa";
}
}
package com.its.swagger.controller;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
@Api(tags = "角色管理") // tags:你可以当作是这个组的名字。
@RestController
public class RoleController {
    
    
@PostMapping("/ww")
public boolean ww(){
    
    
return false;
}
}

Restart to view UI view

view analysis

insert image description here
We can use @ApiOperation to describe the interface, for example:

@ApiOperation(value = "用户测试",notes = "用户测试notes")
@GetMapping("/test")
public String test(String id){
    
    
return "test";
}

Define interface request parameters

The above uses @ApiOperation to describe the interface, but in fact there is still a lack of description of the interface request parameters. Let's talk about it in different scenarios.
Note that for the GET method, swagger does not recommend using the body method to transfer data, that is, it does not want to use
json, form-data, etc. to transfer data in the GET method. At this time, it is best to use path parameters or url parameters. (Although POSTMAN, etc. are supported), so
if the data passed by the interface is in the form of json or form-data, it is better to use the POST method.

The request parameter is an entity class

At this point, we need to use @ApiModel to mark the entity class, and then define the input parameter in the interface as the entity class:
@ApiModel: used to mark the class
Common configuration items:

  1. value: entity class abbreviation
  2. description: entity class description
    @ApiModelProperty: used to describe the meaning of the field of the class.
    Common configuration items:
  3. value: field description
  4. example: Set the default value of the request example (Example Value). If not configured, when the field is string, the
    default value in the request example is "".
  5. name: Replace the old field name with the new field name.
  6. allowableValues: limit the value range, for example, {1,2,3} means that only these three values ​​can be taken; [1,5] means that the value from 1 to 5 is taken; (1,5) means the
    value from 1 to 5, excluding 1 and 5; you can also use infinity or -infinity to infinite value, such as [1, infinity] means the minimum value is 1, and the maximum
    value is infinite.
public class Filter {
    
    
@ApiModelProperty(allowableValues = "range[1,5]")
Integer order
@ApiModelProperty(allowableValues = "111, 222")
String code;
}
  1. required: Whether the tag field is required, the default is false,
  2. hidden: used to hide the field, the default is false, if you want to hide, you need to use true, because the field will be displayed by default, even if there is no
    @ApiModelProperty.
package com.its.swagger.pojo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
// 先使用@ApiModel来标注类
@ApiModel(value="用户登录表单对象",description="用户登录表单对象")
@Data //getter,setter,swagger也需要这个
public class LoginForm {
    
    
// 使用ApiModelProperty来标注字段属性。
@ApiModelProperty(value = "用户名",required = true,example = "root")
private String username;
@ApiModelProperty(value = "密码",required = true,example = "123456")
private String password;
}

defined as an input parameter

@ApiOperation(value = "登录接口",notes = "登录接口的说明")
@PostMapping("/login")
public LoginForm login(@RequestBody LoginForm loginForm){
    
    
return loginForm;
}

insert image description here

The request parameter is a non-entity class

Declare that the input parameter is a URL parameter

Say it again: for the GET method, swagger does not recommend using the body method to pass data, so although Spring MVC can automatically encapsulate
parameters , do not use form-data, json, etc. to pass parameters for GET requests, unless you use Postman to test Interface,
swagger online test does not support this operation.
For non-entity class parameters, you can use @ApiImplicitParams and @ApiImplicitParam to declare request parameters.
@ApiImplicitParams is used in the method header, @ApiImplicitParam is defined in @ApiImplicitParams, and one
@ApiImplicitParam corresponds to one parameter.
Common configuration items for @ApiImplicitParam:

  1. name: The name used to define the parameter, that is, the name of the field, which can correspond to the input parameter name of the interface. If it does not correspond, it will also be generated,
    so it can be used to define additional parameters!
  2. value: used to describe the parameter
  3. required: Used to mark whether the parameter is required
  4. paramType has path, query, body, form, header, etc., but for non-entity parameters, only
    path, query, header are commonly used; body and form are not commonly used. body is not suitable for multiple scattered parameters, only for json
    objects and other situations. [If your interface is form-data, x-www-form-urlencoded, you may not be able to use the swagger page
    API to debug, but you can debug in the swagger enhancement based on BootstrapUI later, and the swagger based on BootstrapUI
    supports specifying form- data or x-www-form-urlencoded]
// 使用URL query参数
@ApiOperation(value = "登录接口2",notes = "登录接口的说明2")
@ApiImplicitParams({
    
    
@ApiImplicitParam(name = "username",//参数名字
value = "用户名",//参数的描述
required = true,//是否必须传入
//paramType定义参数传递类型:有path,query,body,form,header
paramType = "query"
)
,
@ApiImplicitParam(name = "password",//参数名字
value = "密码",//参数的描述
required = true,//是否必须传入
paramType = "query"
)
})
@PostMapping(value = "/login2")
public LoginForm login2(String username,String password){
    
    
System.out.println(username+":"+password);
LoginForm loginForm = new LoginForm();
loginForm.setUsername(username);
loginForm.setPassword(password);
return loginForm;
}

Declare that the input parameter is a URL path parameter

// 使用路径参数
@PostMapping("/login3/{id1}/{id2}")
@ApiOperation(value = "登录接口3",notes = "登录接口的说明3")
@ApiImplicitParams({
    
    
@ApiImplicitParam(name = "id1",//参数名字
value = "用户名",//参数的描述
required = true,//是否必须传入
//paramType定义参数传递类型:有path,query,body,form,header
paramType = "path"
)
,
@ApiImplicitParam(name = "id2",//参数名字
value = "密码",//参数的描述
required = true,//是否必须传入
paramType = "path"
)
})
public String login3(@PathVariable Integer id1,@PathVariable Integer id2){
    
    
return id1+":"+id2;
}

The declared input parameter is the header parameter:

// 用header传递参数
@PostMapping("/login4")
@ApiOperation(value = "登录接口4",notes = "登录接口的说明4")
@ApiImplicitParams({
    
    
@ApiImplicitParam(name = "username",//参数名字
value = "用户名",//参数的描述
required = true,//是否必须传入
//paramType定义参数传递类型:有path,query,body,form,header
paramType = "header"
)
,
@ApiImplicitParam(name = "password",//参数名字
value = "密码",//参数的描述
required = true,//是否必须传入
paramType = "header"
)
})
public String login4( @RequestHeader String username,
@RequestHeader String password){
    
    
return username+":"+password;
}

Declare file upload parameters

// 有文件上传时要用@ApiParam,用法基本与@ApiImplicitParam一样,不过@ApiParam用在参数上
// 或者你也可以不注解,swagger会自动生成说明
@ApiOperation(value = "上传文件",notes = "上传文件")
@PostMapping(value = "/upload")
public String upload(@ApiParam(value = "图片文件", required = true)MultipartFile
uploadFile){
    
    
String originalFilename = uploadFile.getOriginalFilename();
return originalFilename;
}
// 多个文件上传时,**swagger只能测试单文件上传**
@ApiOperation(value = "上传多个文件",notes = "上传多个文件")
@PostMapping(value = "/upload2",consumes = "multipart/*", headers = "contenttype=multipart/form-data")
public String upload2(@ApiParam(value = "图片文件", required = true,allowMultiple =
true)MultipartFile[] uploadFile){
    
    
StringBuffer sb = new StringBuffer();
for (int i = 0; i < uploadFile.length; i++) {
    
    
System.out.println(uploadFile[i].getOriginalFilename());
sb.append(uploadFile[i].getOriginalFilename());
sb.append(",");
}
return sb.toString();
}
// 既有文件,又有参数
@ApiOperation(value = "既有文件,又有参数",notes = "既有文件,又有参数")
@PostMapping(value = "/upload3")
@ApiImplicitParams({
    
    
@ApiImplicitParam(name = "name",
value = "图片新名字",
required = true
)
})
public String upload3(@ApiParam(value = "图片文件", required = true)MultipartFile
uploadFile,
String name){
    
    
String originalFilename = uploadFile.getOriginalFilename();
return originalFilename+":"+name;
}

Define the interface response

The interface response is defined so that people who view the interface document can know the meaning of the data returned by the interface.

The response is an entity class

When defining the interface request parameters, it was mentioned to use @ApiModel to mark the class. If the interface returns this class, then the
description on this class will also be used as the description of the response:

// 返回被@ApiModel标注的类对象
@ApiOperation(value = "实体类响应",notes = "返回数据为实体类的接口")
@PostMapping("/role1")
public LoginForm role1(@RequestBody LoginForm loginForm){
    
    
return loginForm;
}

insert image description here

The response is a non-entity class

swagger cannot describe the response of non-entity classes in detail, but can only mark the response code and other information.
It is achieved through @ApiResponses and @ApiResponse.
@ApiResponses and @ApiResponse can be used together with @ApiModel.

// 其他类型的,此时不能增加字段注释,所以其实swagger推荐使用实体类
@ApiOperation(value = "非实体类",notes = "非实体类")
@ApiResponses({
    
    
@ApiResponse(code=200,message = "调用成功"),
@ApiResponse(code=401,message = "无权限" )
}
)
@PostMapping("/role2")
public String role2(){
    
    
return " {\n" +
" name:\"广东\",\n" +
" citys:{\n" +
" city:[\"广州\",\"深圳\",\"珠海\"]\n" +
" }\n" +
" }";
}

insert image description here

Swagger UI enhancements

You may think that this UI is not very good-looking now, and now some third parties provide some Swagger UI enhancements, the more popular one is
swagger-bootstrap-ui

<!-- 引入swagger-bootstrap-ui依赖包-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.9.6</version>
</dependency>

Add the annotation @EnableSwaggerBootstrapUI to the swagger configuration class:

@Configuration // 标明是配置类
@EnableSwagger2 //开启swagger功能
@EnableSwaggerBootstrapUI // 开启SwaggerBootstrapUI
public class SwaggerConfig {
    
    
// 省略配置内容
}

Visit the API: http://localhost:8080/doc.html to preview the Swagger UI interface based on bootstarp.

Finally, I wrote swagger's CRUD and file upload code examples as follows:

package com.example.controller;

import com.example.pojo.Cargo;
import com.example.service.CargoService;
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.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lixp
 * @since 2023年04月10日
 */

@Api(tags = "李小屁的专属")
@RestController
@RequestMapping("/cargo")
public class CargoController {
    
    

    @Autowired
    private CargoService cargoService;

//    查所有
    @ApiOperation(value = "查询所有",notes = "查所有")
    @ApiImplicitParams({
    
    
            @ApiImplicitParam(name = "username",
                            value = "用户名",
                            required = true,
                            paramType = "query")
    })
    @GetMapping
    public List<Cargo> list() {
    
    
        return cargoService.list();
    }
//    根据id查询
    @GetMapping("/{id}")
    public Cargo getById(@PathVariable Long id){
    
    
        return cargoService.getById(id);
    }
//    删除
    @DeleteMapping
    public boolean delete(@RequestParam Long id){
    
    
        return cargoService.removeById(id);
    }
    //修改
    @PutMapping
    public boolean update(Cargo cargo) {
    
    
        return cargoService.updateById(cargo);
    }

//    文件上传
    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public boolean upload(MultipartFile multipartFile) throws IOException {
    
    
        multipartFile.transferTo(new File("D:\\images\\"+multipartFile.getOriginalFilename()));
        return true;
    }

}

sample graph:
insert image description here

Guess you like

Origin blog.csdn.net/weixin_52859229/article/details/130067783