千峰商城-springboot项目搭建-07-Swagger

2022/5/1 6:13:13

本文主要是介绍千峰商城-springboot项目搭建-07-Swagger,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

前后端分离开发,后端需要编写接口说明文档,会耗费比较多的时间。

swagger是一个用于生成服务器接口说明的规范性文档,并且能够对接口进行测试的工具。

 

 

1.在api子工程的pom中添加依赖 Swagger2、Swagger UI

 

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>3.0.0</version>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>3.0.0</version>
        </dependency>

 

    2.在api子工程创建一个swagger配置类(Java配置方式) 在api子工程下的 src - main - java - com.qfedu.fmmall 中新建一个config包,在config包中创建一个类SwaggerConfig。 SwaggerConfig.java:
package com.qfedu.fmmall.config;

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

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    //1.配置生成的文档信息
    //2.配置生成的接口信息

    //Docket封装接口文档信息
    @Bean
    public Docket getDocket(){

        ApiInfoBuilder apiInfoBuilder = new ApiInfoBuilder();
        apiInfoBuilder.title("《锋迷商城》后端接口说明")
                .description("此文档详细说明了锋迷商城项目后端接口规范。")
                .version("v 2.0.1")
                .contact(new Contact("小白","www.xiaobai.com","xiaobai@qq.com"));


        ApiInfo apiInfo = apiInfoBuilder.build();

//        docket.apiInfo(apiInfo);//指定生成的文档中的封面信息:标题、版本、作者

        Docket docket = new Docket(DocumentationType.SWAGGER_2)//指定文档风格
                .apiInfo(apiInfo)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.qfedu.fmmall.controller"))
                .paths(PathSelectors.any())
                .build();


        return docket;

    }



}

 

      3.测试生成的swagger。

 

 

 

在浏览器中输入网址:http://localhost:8080/swagger-ui.html

 

 

测试成功!



这篇关于千峰商城-springboot项目搭建-07-Swagger的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程