首页 /  技术专区  /  SpringBoot 宽屏模式 >

SpringBoot2.7.14集成Swagger3.0

第一步:导入Maven依赖

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>

第二步:配置application.yaml

spring:
  mvc:
    pathmatch:
      # 引入swagger3.0时加入的配置 localhost:8081/swagger-ui/index.html
      matching-strategy: ant_path_matcher

控制页面开启/关闭

springfox:
  documentation:
    swagger-ui:
      enabled: true

第三步:编写配置类

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;

@Configuration
public class Swagger3Config {

    @Bean
    public Docket createRestApi(){
        //Docket: 摘要对象,通过对象配置 描述文件的信息
        Docket docket = new Docket(DocumentationType.OAS_30);
        docket.apiInfo(myApiInfo())
                //select():返回ApiSelectorBuilder对象,通过对象调用build()可以创建Docket对象
                .select()
                // 指定要扫描/维护接口文档的包(否则就全部扫描)
                .apis(RequestHandlerSelectors.basePackage("com.allen.controller"))
                // 路径过滤:该Docket-UI展示时,只展示指定路径下的接口文档(any表示都展示)
                .paths(PathSelectors.any())
                .build();
        return docket;
    }

    // 接口文档的概要信息,返回ApiInfo对象
    private ApiInfo myApiInfo(){
        //标题
        String title = "系统接口文档";
        //简单描述
        String description = "一个简单明了的接口信息文档";
        //版本
        String version = "V1.0.0";
        // url接口路径前缀
        String termsOfServiceUrl = "/";
        //作者信息
        Contact contact = new Contact("","","");
        //协议
        String license = "The Apache License";
        //协议url
        String licenseUrl = "https://wwww.baidu.com";

        ApiInfo apiInfo =  new ApiInfoBuilder()
                .title(title)
                .description(description)
                .version(version)
                .termsOfServiceUrl(termsOfServiceUrl)
                .contact(contact)
                .license(license)
                .licenseUrl(licenseUrl)
                .build();
        return apiInfo;
    }

}

第四步:启动项目,访问:http://localhost:8081/swagger-ui/index.html

image.png


Swagger常用注解

@Api()

用于类,标识这个类是swagger的资源 ,主要用在controller类上,会在接口文档上显示当前类说明

@ApiOperation()

用于方法,在接口文档上面对接口进行说明,是swagger最主要的注解

@ApiParam()

用于方法,参数,字段说明,在方法上面对参数进行说明,会在接口文档上面显示参数的说明

@ApiModel()

用于类,表示对类进行说明,用于参数用实体类接收时,在接口文档上面会显示这个类里所有字段的说明

@ApiIgnore()

用于类,方法,方法参数,表示这个方法或者类被忽略,即不会显示在接口文档里面

@ApiImplicitParam()

用于方法,表示单独的请求参数,多数时候可以用@ApiParm替代

@ApiImplicitParams()

用于方法,包含多个 @ApiImplicitParam

@ApiResponses

同@ApiImplicitParams() ,用于方法,会在接口文档里面对当前接口返回的信息进行说明 




头像
0/200
图片验证码