栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

第一章 SpringBoot快速开发框架 - 集成Swagger,生成API文档

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

第一章 SpringBoot快速开发框架 - 集成Swagger,生成API文档

作者简介:
 作者:暗夜91
蘭 个人主页:暗夜91的主页
 如果感觉文章写的还有点帮助,请帮忙点个关注,我会持续输出高质量技术博文。


专栏文章:
1、集成Swagger,生成API文档
2、Mysql数据源配置
3、集成Redis
4、Spring Security + JWT实现登录权限认证
5、跨域配置

专栏源码:
针对该专栏功能,对源码进行整理,可以直接下载运行。
源码下载请移步:SpringBoot快速开发框架


一、集成Swagger,生成API文档

在前后端分离的项目中,API文档是非常必要的,一个优秀的API文档能够减少前后端开发人员大量的沟通时间,提高开发效率,因此能够提供优秀的API文档也是一个后端开发人员必备的素质。

目前能够生成API的工具有很多,我们这里使用Swagger作为生成API的工具。Swagger提供了完整的管理、测试和使用API的功能,其实时性对前后端都十分的友好。

1、集成方法 (1)引入依赖

在pom.xml文件中添加Swagger依赖


    io.springfox
    springfox-swagger2
    2.9.2


    io.springfox
    springfox-swagger-ui
    2.9.2


    com.github.xiaoymin
    swagger-bootstrap-ui
    1.9.1

(2)在application.yml中配置Swagger是否可用
swagger:
  enable: true

注:

Swagger提供对外接口,所以应该只用于开发测试环境,以上配置在生产环境中应设置为false

(3)在工程中添加Swagger配置文件
package com.lll.framework.config;

import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;


@Configuration
@EnableSwagger2
public class SwaggerConfig extends WebMvcConfigurationSupport {

    @Value("${swagger.enable}")
    private boolean enableSwagger;

    
    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("RESTful API")
                .version("1.0")
                .description("API 描述")
                .build();
    }

    @Bean
    public Docket docket(){
        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).enable(enableSwagger).select()
                // 扫描所有有注解的api,用这种方式更灵活
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build();

    }

    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 解决静态资源无法访问
        registry.addResourceHandler("
    public static Predicate basePackage(final String basePackage) {
        return input -> declaringClass(input).transform(handlerPackage(basePackage)).or(true);
    }

    private static Function, Boolean> handlerPackage(final String basePackage)     {
        return input -> {
            // 循环判断匹配
            for (String strPackage : basePackage.split(splitor)) {
                boolean isMatch = input.getPackage().getName().startsWith(strPackage);
                if (isMatch) {
                    return true;
                }
            }
            return false;
        };
    }

    private static Optional> declaringClass(RequestHandler input) {
        return Optional.fromNullable(input.declaringClass());
    }
(3)对swagger中的请求添加全局参数

在实际开发中,后端对外提供的接口应该是有权限验证的,需要提供token验证请求的合法性,为了能够在Swagger中对接口进行测试工作,需要给所有的接口添加全局token参数,具体实现如下:

    @Bean
    public Docket docket(){
        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).enable(enableSwagger).select()
                // 扫描所有有注解的api,用这种方式更灵活
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build()
                .globalOperationParameters(getParam());
    }

private List getParam(){
        ParameterBuilder ticketPar = new ParameterBuilder();
        List pars = new ArrayList();
        
        ticketPar.name("Authorization").description("user ticket")
                .modelRef(new ModelRef("string")).parameterType("header")
                .required(true).build();
        pars.add(ticketPar.build());
        return pars;
    }
3、Swagger常用注解 (1)在Controller上注解

//1.在类上应用的注解:

@Api(tags = “这是一个控制器类”)

//2.在具体请求方法上的注解:

@ApiOperation(value = “功能总述” , notes = “具体描述”)

@ApiParam(value = “请求参数说明”)

(2)在实体类上的注解

//1.在类上应用的注解:

@ApiModel(description = “XX实体类”)

//2.在实体类属性上应用的注解:

@ApiModelProperty(value = “属性说明”)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/851410.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号