您好,欢迎来到爱问旅游网。
搜索
您的当前位置:首页swagger-ui 使用

swagger-ui 使用

来源:爱问旅游网
  • pom引入
    需要注意版本文体,版本不一致,具体使用的坑也不一致…
<dependency>
   <groupId>io.springfox</groupId>
   <artifactId>springfox-swagger2</artifactId>
   <version>2.8.0</version>
</dependency>
<dependency>
   <groupId>io.springfox</groupId>
   <artifactId>springfox-swagger-ui</artifactId>
   <version>2.8.0</version>
</dependency>

整合swagger-ui

# 在application.yml 中加入swagger-ui 的开启或关闭配置
# swagger 文档配置 false关闭 true 开启
swagger:
  enable: true

配置

/**
 * SwaggerConfig 配置
 * @author zy
 */
@Configuration
// 此处增加了该注解以后,不需要再启动类上增加额外注解,会二次创建bean 导致异常
@EnableSwagger2
// 此处与application中swagger-ui配置的名称一致即可完成开启与关闭
@ConditionalOnProperty(name = "enable",prefix = "swagger", havingValue = "true")
public class SwaggerConfig {

    /**
     * 构建配置
     */
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("修改为controller的包路径即可"))
                .paths(PathSelectors.any())
                .build()
                .apiInfo(apiInfo())
                .securitySchemes(Collections.singletonList(securityScheme()))
                .securityContexts(Collections.singletonList(securityContext()));
    }

    /**
     * 文档描述
     */
    private ApiInfo apiInfo() {
        return new ApiInfo(
                "xxx api文档",
                "",
                "1.0",
                "",
                new Contact("", "", ""),
                "", "", Collections.emptyList());
    }

    /**
     * 整合Oauth 使用的对应的方式进行授权
     */
    private SecurityScheme securityScheme() {
        GrantType grantType = new ResourceOwnerPasswordCredentialsGrant(  "/oauth/token");

        return new OAuthBuilder()
                .name("spring_oauth")
                .grantTypes(Collections.singletonList(grantType))
                .scopes(Arrays.asList(scopes()))
                .build();
    }

    /**
     *安全上下文
     */
    private SecurityContext securityContext() {
        return SecurityContext.builder()
                              .securityReferences(Collections.singletonList(new SecurityReference("spring_oauth", scopes())))
                              .forPaths(PathSelectors.any())
                              .build();
    }

    /**
     * 这里是写允许认证的scope
     */
    private AuthorizationScope[] scopes() {
        return new AuthorizationScope[]{
                new AuthorizationScope("select", "select scope is trusted!")
        };
    }

}

具体使用,个人有个人的使用方法。在开发中接口参数通常使用的实体类接收参数,而简单实用swagger-ui 会导致出现很多不需要的参数,以下是针对此问题的部分调整,会导致post测试提交失败,但是好看。

// 在swagger-ui的配置项中,另一种配置不是进行包扫描,而是扫描所有的带@Api注解的接口,具体根据实际使用
@Api(tags = "TestController", description = "测试")
@RestController
@RequestMapping("/api/test")
public class TestController extends ApiController {


    @ApiOperation("测试get方法参数")
    @ApiResponses({
            @ApiResponse(code = 1000, message = "操作成功", response = AjaxResult.class),
            @ApiResponse(code = 1001, message = "操作失败,以及操作失败原因")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "chatId", value = "群组id", required = true, paramType = "query", dataType = "String"),
    })
    @GetMapping("/getAll")
    public AjaxResult getAll(String chatId) {
        return AjaxResult.success();
    }

    @ApiOperation("测试Post方法参数")
    @ApiResponses({
            @ApiResponse(code = 1000, message = "操作成功"),
            @ApiResponse(code = 1001, message = "操作失败,以及操作失败原因")
    })
    // 页面上仅会展示以下两个参数,试过paramType换成body 也会产生部分问题,暂未解决
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "群组名称", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "remarks", value = "群组描述", required = false, paramType = "query", dataType = "String"),
    })
    @PostMapping("/add")
    // @ApiIgnore该注解可以忽略 ChatGroup 中的参数,仅使用ApiImplicitParams上定义的参数
    public AjaxResult add(@ApiIgnore @RequestBody TestEntity testEntity ) {
       return AjaxResult.success();
    }
}
@Data
@EqualsAndHashCode(callSuper = false)
@NoArgsConstructor
@AllArgsConstructor
@ApiModel(value = "测试")
public class TestEntity extends Entity {
    @ApiModelProperty("主键")
    private String id;
    @ApiModelProperty("更新时间")
    private String updateTime;
    // hidden 为true的时候,页面上不会显示该参数,一般用于不需要传参的字段
    @ApiModelProperty(value = "更新人",hidden = true)
    private String updateBy;
}

访问页面

localhost:8080/{项目路径}/swagger-ui.html
# aouth 认证 密码方式

![认证](https://img-blog.csdnimg.cn/35e6a20506ed4923aba3f809a9c779e9.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAenlwYXNzZW5nZXI=,size_20,color_FFFFFF,t_70,g_se,x_16)



因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- awee.cn 版权所有 湘ICP备2023022495号-5

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务