springboot集成swagger

一.swagger概述

swagger是一个用于设计、构建和文档化 RESTful API 的开源框架。它提供了一组工具,使得开发人员能够更轻松地定义、描述和测试API接口,它主要包括四大组件。

 Swagger规范: 定义了一种格式化的API规范,使用YAML或JSON格式,用于描述API的各种细节,包括路由、参数、返回值等。


 

- Swagger编辑器: 提供了一个交互式的编辑界面,让开发人员能够方便地编写和验证Swagger规范文件。


 

- Swagger UI: 一个动态生成的HTML文件,可以将Swagger规范文件渲染成一个美观易用的API文档网页。通过Swagger UI,开发人员可以直观地查看API接口的详细信息,包括请求示例、响应模型和参数说明。


 

- Swagger Codegen: 一个自动生成API客户端代码的工具,根据Swagger规范文件,它可以生成多种编程语言的代码框架,帮助开发人员快速集成和调用API接口。

二,使用swagger

1.首先导入依赖


    io.springfox
    springfox-swagger2
    2.9.2




    io.springfox
    springfox-swagger-ui
    2.9.2

2.添加配置类,

@Configuration
@EnableSwagger2 //标记项目启用 Swagger API 接口文档
public class SwaggerConfig
{

    /** 是否开启swagger */
//    @Value("${swagger.enabled}")
    private boolean enabled = true;

    /** 设置请求的统一前缀 */
//    @Value("${swagger.pathMapping}")
//    private String pathMapping;

    /**
     * 创建API
     */
    @Bean
    public Docket createRestApi()
    {   // 创建Docket对象
        return new Docket(DocumentationType.SWAGGER_2) // 文档类型,使用Swagger2
                // 是否启用Swagger
                .enable(enabled)
                // 用来创建该API的基本信息,展示在文档的页面中(自定义展示的信息)
                // 设置Api信息
                .apiInfo(apiInfo())
                // 设置哪些接口暴露给Swagger展示
                .select()
                // 扫描所有有注解的api,用这种方式更灵活
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                // 扫描指定包中的swagger注解
                // .apis(RequestHandlerSelectors.basePackage("com.project.tool.swagger"))
                // 扫描所有
                .paths(PathSelectors.any())
                // 构建出 Docket 对象
                .build()
                /* 设置安全模式,swagger可以设置访问token */
                .securitySchemes(securitySchemes())
                .securityContexts(securityContexts());
//                .pathMapping(pathMapping);
    }

    /**
     * 安全模式,这里指定token通过Authorization头请求头传递
     */
    private List securitySchemes()
    {
        List apiKeyList = new ArrayList();
        apiKeyList.add(new ApiKey("Authorization", "Authorization", "header"));
        return apiKeyList;
    }

    /**
     * 安全上下文
     */
    private List securityContexts()
    {
        List securityContexts = new ArrayList<>();
        securityContexts.add(
                SecurityContext.builder()
                        .securityReferences(defaultAuth())
                        .forPaths(PathSelectors.regex("^(?!auth).*$"))
                        .build());
        return securityContexts;
    }

    /**
     * 默认的安全上引用
     */
    private List defaultAuth()
    {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        List securityReferences = new ArrayList<>();
        securityReferences.add(new SecurityReference("Authorization", authorizationScopes));
        return securityReferences;
    }

    /**
     * 添加摘要信息
     */
    private ApiInfo apiInfo()
    {
        // 用ApiInfoBuilder进行定制
        return new ApiInfoBuilder()
                // 设置标题
                .title("标题:Swagger测试_接口文档")
                // 描述
                .description("描述:用于管理人员信息,具体包括XXX,XXX模块...")
                // 作者信息
                .contact(new Contact("fyt", null, null))
                // 版本
                .version("版本号:1.0" )
                .build();
    }
}

3.编写controller

springboot集成swagger_第1张图片

 4.启动项目。然后浏览器访问 http://127.0.0.1:4000/swagger-ui.html (`4000是你项目端口`)地址,就可以看到 Swagger 生成的 API 接口文档。如下:

 springboot集成swagger_第2张图片

 为什么文档中有这么多条接口信息,因为swagger是基于RESTful 风格的框架, 但controller中映射路径使用的是@RequestMapper注解,表示可以接收所有请求,所以swagger把每个请求方式都展示出来了。

5.报错

如果出现报错信息

org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException

表示springboot版本和swagger版本不符合。一般swagger2只支持springboot2.5以下的版本,但我们通常不改变springboot版本,所以可以在application.yml中添加以下配置:

spring:

  mvc:

    pathmatch:

      matching-strategy: ant_path_matcher

你可能感兴趣的:(spring,boot,swagger)