SpringBoot整合Swagger2

Posted HQ

tags:

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

Swagger2注解:

  1.@Api:标记类  例:@Api(value="测试类",tags="测试类")

  2.@ApiOperation:标记方法  例:@ApiOperation(value="测试方法",tags="测试方法")

  3.@ApiImplicitParam:用来描述单个参数  例:@ApiImplicitParam(name = "enddate", value = "测试参数3", dataType = "String")

  4.@ApiImplicitParams:用来描述多个参数多个用,分割  例:

@ApiImplicitParams({
      @ApiImplicitParam(name = "projectinfoid", value = "测试参数", dataType = "String"),
      @ApiImplicitParam(name = "startdate", value = "测试参数2", dataType = "String"),
      @ApiImplicitParam(name = "enddate", value = "测试参数3", dataType = "String")
})

   5.@ApiModel :用来描述实体类  @ApiModel(value="测试类")

   6.@ApiModelProperty :用来描述类中的属性 @ApiModelProperty(value="属性名")

 

 

Swagger2配置:

1.在pom.xml中引入依赖

 <!-- swagger -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.2.2</version> <!--这里用的是2.2.2版本,也可以用2.9.2-->
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.2.2</version> <!--这里用的是2.2.2版本,也可以用2.9.2-->
        </dependency>

 

2.创建Swagger配置文件类 SwaggerConfig

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()                    //指定的是要扫描的包,现在是只要在这个包下的类都会生成接口文档
                .apis(RequestHandlerSelectors.basePackage("com.hhtl.backend.controller"))
          .apis(
RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))//这个是设置只有加上Api注解的类才会生成接口文档
          .paths(PathSelectors.any())
          .build();
        }
private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("EasyWeb API文档")
                .description("前后端分离开发平台")
                .termsOfServiceUrl("")
                .contact("https://easyweb.vip")
                .version("1.0")
                .build();
    }
}

 

3.在类上加上注解

@Api(value = "测试类")
@RestController
@RequestMapping(value = "test")
public class TestController {

    @ApiOperation(value = "测试方法")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "projectinfoid", value = "测试参数", dataType = "String"),
            @ApiImplicitParam(name = "startdate", value = "测试参数2", dataType = "String"),
            @ApiImplicitParam(name = "enddate", value = "测试参数3", dataType = "String")
    })
    @GetMapping(value = "queryTest")
    public Result queryTest(@RequestParam String projectinfoid, String startdate, String enddate){
        try {
            return Result.ok();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error();
    }

 

4.访问http://localhost:8080/swagger-ui.html 就可以看到接口页面

 或访问http://192.168.79.1:8080/doc.html

 

 

现在的Swagger-ui 的页面所有人都可以访问不是很安全,可以改成需要输入密码才可以访问

 

1.引入协议

 

    <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>swagger-bootstrap-ui</artifactId>
            <version>1.9.3</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-bean-validators</artifactId>
            <version>2.9.2</version>
        </dependency>

 

2.在application.yml中配置账号密码

swagger:
  basic:
    enable: true
    ## Basic认证用户名
    username: 123
    ## Basic认证密码
    password: 123

3.在SwaggerConfig类上加上@EnableSwaggerBootstrapUI注解

@Configuration
@EnableSwagger2
@EnableSwaggerBootstrapUI
public class SwaggerConfig {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.hhtl.backend.controller"))
                //加了ApiOperation注解的类,才生成接口文档
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("EasyWeb API文档")
                .description("前后端分离开发平台")
                .termsOfServiceUrl("")
                .contact("https://easyweb.vip")
                .version("1.0")
                .build();
    }
}

 

请求头中需要加参数的话在创建Docket对象的时候增加.globalOperationParameters(参数集合) 

package com.hhtl.backend.config;

import com.github.xiaoymin.swaggerbootstrapui.annotations.EnableSwaggerBootstrapUI;
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
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.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;

@Configuration
@EnableSwagger2
@EnableSwaggerBootstrapUI
public class SwaggerConfig {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.hhtl.backend.controller"))
                //加了ApiOperation注解的类,才生成接口文档
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build()
                .globalOperationParameters(setHeaderToken());//请求头所需参数
    }

    private List<Parameter> setHeaderToken() {
        ParameterBuilder tokenPar = new ParameterBuilder();
        List<Parameter> pars = new ArrayList<>();
        tokenPar.name("token").description("token").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
        pars.add(tokenPar.build());
        return pars;
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("EasyWeb API文档")
                .description("前后端分离开发平台")
                .termsOfServiceUrl("")
                .contact("https://easyweb.vip")
                .version("1.0")
                .build();
    }


}

 

再次打开Swagger-ui页面就可以看到

 

 

 

 

 

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

Swagger2springboot整合swagger2

SpringBoot整合Swagger2

SpringBoot整合Swagger2

SpringBoot整合Swagger2简单的例子

5分钟 springboot 整合swagger2

SpringBoot整合Swagger2