小言_互联网的博客

使用Swagger实现接口文档

441人阅读  评论(0)

一、简介

在项目开发中,一般都是前后端分离,所有前后端工程师需要共同定义接口,编写接口文档,之后根据文档进行开发和维护。
为了编写和维护稳定,可以使用Swagger来编写API接口文档,提高效率

二、配置Swagger

1、添加Swagger依赖

  <!-- Swagger 依赖-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <!-- Swagger-UI 依赖-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>

2、创建Swagger配置类

在spirng boot集成时,放在与springbootApplication的同级目录下

package com.atmae.agriculture;

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.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * @Author: Mae
 * @Date: 2022/3/9
 * @Time: 20:44
 * @Description:
 */
@Configuration
@EnableSwagger2
public class Swagger2 {
   

    /**
     * 创建API应用
     * 通过select函数返回一个APiSelectorBuilder实例,用来控制哪些接口暴露给Swagger来展现
     * 本例使用的是 扫描包路径指定要展现的接口
     * @return
     */
    @Bean
    public Docket createRestApi(){
   
        return new Docket(DocumentationType.SPRING_WEB)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.atmae.agriculture.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    /**
     * 创建该API的基本信息(这些信息会展现给文档首页)
     * @return
     */
    private ApiInfo apiInfo() {
   
        return new ApiInfoBuilder()
                .title("系统开发 API")
                .description(("这是系统开发API 前后端共同定义"))
                .termsOfServiceUrl("http://localhost:8090/")
                .version("1.0")
                .build();
    }
}

注意:如果报一下错误,则说明你的Springboot 版本过高。
笔者使用的 2.6.4 换成了 2.5.1 错误就没了

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

三、访问http://localhost:8090/swagger-ui.html/

端口号根据自己的程序来确定。
注意:如果设置了访问权限 一定要给swagger的资源放行




转载:https://blog.csdn.net/weixin_51799151/article/details/123386931
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场