【工具】springboot集成swagger(接口文档工具)

复杂的事情简单化,大神封装好了,我们拿来直接用就好:只需
(1)依赖
(2)创建一个配置文件
在这里插入图片描述

1.pom.xml导入依赖

注意springboot版本和swagger的版本,我springboot版本是2.4.0

	<!--swagger的依赖-->
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger-ui</artifactId>
			<version>2.9.2</version>
		</dependency>

		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger2</artifactId>
			<version>2.9.2</version>
		</dependency>

2.swagger的访问路径

http://ip:端口号/swagger-ui.html(例如:http://localhost:8086/swagger-ui.html)

3.创建配置文件:常用的配置汇总(具体释义可查看案例)

package com.example.common;  //这里根据项目实际包路径修改

import cn.hutool.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Autowired
    Environment environment;

    @Bean
    public Docket docket() {  //这个是在swagger-ui这个依赖中
        //配置哪些环境可以访问swagger
        Profiles profiles = Profiles.of("dev", "test");
        boolean isEnable = environment.acceptsProfiles(profiles);

        Parameter token = new ParameterBuilder().name("token")
                .description("用户登录令牌")
                .parameterType("query") //如果改成header,则接收token时需要写@RequestHeader("token")String token
                .modelRef(new ModelRef("String"))
                .required(true)  //代表此字段必填
                .build();
        List<Parameter> parameters = new ArrayList<>();
        parameters.add(token);

        return new Docket(DocumentationType.SWAGGER_2)
                /*配置哪些环境可以访问swagger*/
                .enable(isEnable)
                /*配置全局参数*/
                .globalOperationParameters(parameters)

                /*配置忽略一些参数*/
                .ignoredParameterTypes(HttpServletRequest.class, HttpResponse.class)

                /*配置swagger页面的基本信息*/
                .apiInfo(apiInfo())

                /*下面为一些配置*/
                .select()
                //扫描controller层的包
                .apis(RequestHandlerSelectors.basePackage("com.example.controller"))
                //过滤:设置请求路径,这里是带有admin的请求路径,注意需要加上前缀
                // .paths(PathSelectors.ant("/api/admin/**"))
                .build();
    }

    private ApiInfo apiInfo() {
        Contact concat = new Contact("后端管理系统", "springboot后端接口", "163.com");
        return new ApiInfo(
                "SpringBoot项目集成Swagger实例文档",
                "欢迎",
                "API V1.0",
                "可修改成公司或组织的域名",   //公司或组织的url
                concat,
                "",
                "",
                Collections.emptyList());
    }


    //如果使用分组就是设置不同的对象
    @Bean
    public Docket docket1() {  //这个是在swagger-ui这个依赖中
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("第一组")
                .select().paths(PathSelectors.ant("/api/admin/**")).build();
    }
    @Bean
    public Docket docket2() {  //这个是在swagger-ui这个依赖中
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("第2组")
                .select().paths(PathSelectors.ant("/api/audit/**")).build();
    }
}

4.案例

实际项目中swagger配置文件中用不到的属性可以注释掉

4.1 页面基本信息部分:调用apiInfo

在这里插入图片描述

   @Bean
    public Docket docket() { 
        return new Docket(DocumentationType.SWAGGER_2)
                /*配置swagger页面的基本信息*/
                .apiInfo(apiInfo())
                .build();
    }

//可以根据需要配置相关的值
    private ApiInfo apiInfo() {
        Contact concat = new Contact("后端管理系统", "springboot后端接口", "163.com");
        return new ApiInfo(
                "SpringBoot项目集成Swagger实例文档",
                "欢迎",
                "API V1.0",
                "可修改成公司或组织的域名",   //公司或组织的url
                concat,
                "",
                "",
                Collections.emptyList());
    }

在这里插入图片描述

4.2 接口部分

(1)apis:com.example.controller为包路径,不加过滤pahts时代表扫描所有controller层接口
(2)paths:/api/admin/** 为指定的接口范围(项目中有api前缀的必须加上)

 @Bean
    public Docket docket() {  //这个是在swagger-ui这个依赖中
        return new Docket(DocumentationType.SWAGGER_2)
       
                /*下面为一些配置*/
                .select()
                //扫描controller层的包
                .apis(RequestHandlerSelectors.basePackage("com.example.controller"))
                //过滤:设置请求路径,这里是带有admin的请求路径,注意需要加上前缀
                 .paths(PathSelectors.ant("/api/admin/**"))
                .build();
    }

apis、paths其他的属性根据不同的需要去选择
在这里插入图片描述

4.3配置忽略一些参数

比如下面的示例,查看接口文档时就看不到request response参数

.ignoredParameterTypes(HttpServletRequest.class, HttpResponse.class)

4.4 配置全局参数

比如配置一个全局的token

 @Bean
    public Docket docket() {  //这个是在swagger-ui这个依赖中
    
        Parameter token = new ParameterBuilder().name("token")
                .description("用户登录令牌")
                //如果query改成header,则接收token时需要写public Result findList(@RequestHeader("token")String token){}
                .parameterType("query") 
                .modelRef(new ModelRef("String"))
                .required(true)  //必填
                .build();
        List<Parameter> parameters = new ArrayList<>();
        parameters.add(token);

        return new Docket(DocumentationType.SWAGGER_2)
                /*配置全局参数*/
                .globalOperationParameters(parameters)

                /*下面为一些配置*/
                .select()
                //扫描controller层的包
                .apis(RequestHandlerSelectors.basePackage("com.example.controller"))
                //过滤:设置请求路径,这里是带有admin的请求路径,注意需要加上前缀
                 .paths(PathSelectors.ant("/api/admin/**"))
                .build();
    }

4.5配置哪些环境可以访问swagger

(1)写成public Docket docket( Environment environment) 与 @Autowired注入的方式是一样的
(2)先参考spingboot多环境配置https://blog.csdn.net/qq_37449606/article/details/138161809

 @Autowired
    Environment environment;

    @Bean
    public Docket docket() {  //这个是在swagger-ui这个依赖中
        //配置哪些环境可以访问swagger
        Profiles profiles = Profiles.of("dev", "test");
        boolean isEnable = environment.acceptsProfiles(profiles);

        return new Docket(DocumentationType.SWAGGER_2)
                /*配置哪些环境可以访问swagger*/
                .enable(isEnable)
                .build();
    }

4.6分组

每个组下面放什么接口可以自定义
实现:创建多个bean对象
在这里插入图片描述

    //如果使用分组就是设置不同的对象
    @Bean
    public Docket docket1() {  //这个是在swagger-ui这个依赖中
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("第一组")
                .select().paths(PathSelectors.ant("/api/admin/**")).build();
    }
    @Bean
    public Docket docket2() {  //这个是在swagger-ui这个依赖中
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("第2组")
                .select().paths(PathSelectors.ant("/api/audit/**")).build();
    }

5.注解

实体类的注解
@ApiModel
@ApiModelProperty
controller层接注解
@Api
@ApiOperation
@ApiImplicitParams
@ApiImplicitParam

5.1实体中的注解

更加方便阅读
@ApiModel(“用户实体”) 【定义实体的名称】
@ApiModelProperty(value=“用户名” , example =“zhangs” ) 【定义属性的名称,example为示例】

@Data
@Table(name = "admin")
@ApiModel("用户实体")
public class Admin {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @ApiModelProperty(value="用户名" , example ="zhangs" )
    private String name;
    @ApiModelProperty("密码")
    private String password;
    private Integer age;
    private String phone;
    private String sex;
    private String role;
}

在这里插入图片描述
在这里插入图片描述

5.2controller注解

@Api
@ApiOperation
@ApiImplicitParams
@ApiImplicitParam

@Api(tags ="用户相关的请求")
@RestController
@RequestMapping("/admin")
public class AdminController {

    @ApiOperation("查询用户接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "用户名", dataType = "String", paramType = "header", defaultValue = "zhangsan", example = "lisa"),
            @ApiImplicitParam(name = "password", value = "密码", dataType = "String", paramType = "header", defaultValue = "zhangsan", example = "lisa")
    })
    @GetMapping("/findUserTest")
    public Admin findUserList(String name, String password){
        return new Admin(1,"zhangsan","123456",15,"176","女","role","","");
    }

    @ApiOperation("用对象格式接收的接口")
    @GetMapping("/findUserTest2")
    public Admin findUserList2(Admin admin){
        return new Admin(1,"zhangsan","123456",15,"176","女","role","","");
    }

    @ApiOperation("用json格式接收的接口")
    @GetMapping("/findUserTest3")
    public Admin findUserList3(@RequestBody  Admin admin){
        return new Admin(1,"zhangsan","123456",15,"176","女","role","","");
    }
}

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 15
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

妄忧杂记

整理不易,请多多打赏

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值