SpringBoot整合Swagger2

Posted mry6

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot整合Swagger2相关的知识,希望对你有一定的参考价值。

Swagger2介绍

前后端分离开发模式中,api文档是最好的沟通方式。
Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。

maven依赖

创建一个Spring Boot项目,加入web依赖,加入两个Swagger2相关的依赖,依赖如下:

<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>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>

Swagger2配置

配置方式一

package com.example.springboot.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.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 createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .pathMapping("/")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.springboot.controller"))
                .paths(PathSelectors.any())
                .build().apiInfo(new ApiInfoBuilder()
                        .title("SpringBoot整合Swagger")
                        .description("SpringBoot整合Swagger,详细信息......")
                        .version("9.0")
                        .contact(new Contact("发邮件","blog.csdn.net","aaa@gmail.com"))
                        .license("The Apache License")
                        .licenseUrl("http://www.baidu.com")
                        .build());
    }

}

配置方式二

package com.example.springboot.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
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;

@Configuration
@EnableSwagger2
public class SwaggerConfig implements WebMvcConfigurer {

    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //为当前包下controller生成API文档
                //.apis(RequestHandlerSelectors.basePackage("com.troila"))
                //为有@Api注解的Controller生成API文档
                //.apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
                //为有@ApiOperation注解的方法生成API文档
                //.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                //为任何接口生成API文档
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
                //添加登录认证
                /*.securitySchemes(securitySchemes())
                .securityContexts(securityContexts());*/
    }

    private ApiInfo apiInfo() {
        Contact contact = new Contact("mu", "", "mu****@gmail.com");
        return new ApiInfoBuilder()
                .title("SwaggerUI演示")
                .description("接口文档,描述词省略200字")
                .contact(contact)
                .version("1.0")
                .build();
    }

    /**
     * 配置swagger2的静态资源路径
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //解决静态资源无法访问
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/static/");
        //解决swagger无法访问
        registry.addResourceHandler("/swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        //解决swagger的js文件无法访问
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}

参数说明:
(1) 为当前配置的包下controller生成API文档

.apis(RequestHandlerSelectors.basePackage("com.example.springboot.controller"))

(2) 为有@Api注解的Controller生成API文档

.apis(RequestHandlerSelectors.withClassAnnotation(Api.class))

(3) 为有@ApiOperation注解的方法生成API文档

.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))

启动项目,输入http://localhost:8080/swagger-ui.html,能够看到如下页面,说明已经配置成功了:
在这里插入图片描述

接口创建

package com.example.springboot.controller;
import com.example.springboot.model.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

@RestController
@Api(tags = "用户管理相关接口")
@RequestMapping("/user")
public class UserController {

    @RequestMapping("/add")
    @ApiOperation("添加用户的接口")
    public String addUser(@RequestBody User user) {
        return "用户添加成功";
    }

    @RequestMapping("/")
    @ApiOperation("根据id查询用户的接口")
    @ApiImplicitParam(name = "id", value = "用户id", defaultValue = "99", required = true)
    public User getUserById(@PathVariable Integer id) {
        User user = new User();
        user.setId(id);
        return user;
    }

    @RequestMapping("/{id}")
    @ApiOperation("根据id更新用户的接口")
    public User updateUserById(@RequestBody User user) {
        return user;
    }

}

实体类创建

package com.example.springboot.model;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

@ApiModel
public class User {

    @ApiModelProperty(value = "用户id")
    private Integer id;
    @ApiModelProperty(value = "用户名")
    private String username;
    @ApiModelProperty(value = "用户地址")
    private String address;

    public Integer getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

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

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

}

经过如上配置之后,可以看到如下效果:
在这里插入图片描述

Swagger2注解说明

1、@Api :请求类的说明
@Api:放在请求的类上,与 @Controller 并列,说明类的作用,如用户模块,订单类等。
tags=“说明该类的作用”
value=“该参数没什么意义,所以不需要配置”

@RestController
@Api(tags = "用户管理相关接口")
@RequestMapping("/user")
public class UserController {
	//TODO
}

2、@ApiOperation:方法的说明
@ApiOperation:“用在请求的方法上,说明方法的作用”
value=“说明方法的作用”
notes=“方法的备注说明”

@RequestMapping("/add")
@ApiOperation("添加用户的接口")
 public String addUser(@RequestBody User user) {
     return "用户添加成功";
 }

3、@ApiImplicitParams、@ApiImplicitParam:方法参数的说明
@ApiImplicitParams:用在请求的方法上,包含一组参数说明
@ApiImplicitParam:对单个参数的说明
name:参数名
value:参数的汉字说明、解释
required:参数是否必须传
paramType:参数放在哪个地方
· header --> 请求参数的获取:@RequestHeader
· query --> 请求参数的获取:@RequestParam
· path(用于restful接口)–> 请求参数的获取:@PathVariable
· body(请求体)–> @RequestBody User user
· form(普通表单提交)
dataType:参数类型,默认String,其它值dataType=“int”
defaultValue:参数的默认值

@PostMapping("/")
@ApiOperation("添加用户的接口")
@ApiImplicitParams({
        @ApiImplicitParam(name = "username", value = "用户名", defaultValue = "李四"),
        @ApiImplicitParam(name = "address", value = "用户地址", defaultValue = "深圳", required = true)
}
)
public RespBean addUser(String username, @RequestParam(required = true) String address) {
    return new RespBean();
}

4、@ApiModel:用于JavaBean上面,表示一个JavaBean

@ApiModel
public class User {
	//TODO
}

5、@ApiModelProperty:用在JavaBean的属性上面,说明属性的含义

@ApiModel
public class User {

    @ApiModelProperty(value = "用户id")
    private Integer id;
    @ApiModelProperty(value = "用户名")
    private String username;
    @ApiModelProperty(value = "用户地址")
    private String address;
}

遇到问题

1.问题描述
一个接口出现多种方式的请求,如下图所示:
在这里插入图片描述
解决方案:
造成这个问题的原因是因为没有给接口指定请求方式。

package com.example.springboot.controller;

import com.example.springboot.model.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;

@RestController
@Api(tags = "用户管理相关接口")
@RequestMapping("/user")
public class UserController {

    @ApiOperation("添加用户的接口")
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    @ResponseBody
    public String addUser(@RequestBody User user) {
        return "用户添加成功";
    }

    @RequestMapping(value = "/",method = RequestMethod.GET)
    @ApiOperation("根据id查询用户的接口")
    @ApiImplicitParam(name = "id", value = "用户id", defaultValue = "99", required = true)
    public User getUserById(@PathVariable Integer id) {
        User user = new User();
        user.setId(id);
        return user;
    }

    @RequestMapping(value = "/{id}",method = RequestMethod.POST)
    @ApiOperation("根据id更新用户的接口")
    public User updateUserById(@RequestBody User user) {
        return user;
    }

    @ApiOperation("获取表是否存在")
    @RequestMapping(value = "/getTable",method = RequestMethod.GET)
    public int getTable(@ApiParam(name = "tableName", value = "表名", required = true)@RequestParam String tableName){
        return 0;
    }

}

如上述代码一样,根据实际情况给每个方法指定 method 参数就可以。执行结果如下图所示:
在这里插入图片描述

以上是关于SpringBoot整合Swagger2的主要内容,如果未能解决你的问题,请参考以下文章

Swagger2springboot整合swagger2

SpringBoot整合Swagger2

SpringBoot整合Swagger2

SpringBoot整合Swagger2简单的例子

5分钟 springboot 整合swagger2

SpringBoot整合Swagger2