Spring-Boot工程集成Swagger2

声明:

此文章只讲述Spring-Boot如何集成和使用Swagger2


下面开始具体步骤:

第一步:导入依赖jar包

建议直接在父工程的pom文件中导入,其下的子工程都可以直接使用,无需再次导包,方便

<dependency>

    <groupId>io.springfox</groupId>

    <artifactId>springfox-swagger-ui</artifactId>

    <version>2.9.2</version>

</dependency>

<dependency>

    <groupId>io.springfox</groupId>

    <artifactId>springfox-swagger2</artifactId>

    <version>2.9.2</version>

</dependency>

第二步:编写Swagger的配置类

在所需要使用swagger的子工程里编写此配置类

@Configuration

@EnableSwagger2

public class Swagger2Configuration {

    //api接口包扫描路径

    public static final String SWAGGER_SCAN_BASE_PACKAGE = "com.changgou.goods";

    public static final String VERSION = "1.0.0";

    @Bean

    public Docket createRestApi() {

        return new Docket(DocumentationType.SWAGGER_2)

                    .apiInfo(apiInfo())

                    .select()                     

                    .apis(RequestHandlerSelectors.basePackage(SWAGGER_SCAN_BASE_PACKAGE))                     .paths(PathSelectors.any()) // 可以根据url路径设置哪些请求加入文档,忽略哪些请求

                    .build();

}

    private ApiInfo apiInfo() {

        return new ApiInfoBuilder()

                    .title("单词计数服务") //设置文档的标题

                    .description("单词计数服务 API 接口文档") // 设置文档的描述

                    .version(VERSION) // 设置文档的版本信息-> 1.0.0 Version information                   

                    .termsOfServiceUrl("http://www.baidu.com") // 设置文档的License信息->1.3 Licensinformation

                    .build();

    }

}


第三步:开始使用

浏览器输入:

http://localhost:9001/swagger-ui.html

即可访问,注意:ip和端口根据自身启动的项目编写

登陆成功后显示如下图:

展开类维度的接口列表,如brand-controller,页面会列出该类中定义的所有接口。点击任意接口,可查看该接口的 url 路径、请求类型、参数描述和返回码说明等信息。


这里我们来测试一下findById这个接口



点击Try it out可以传入参数进行测试



注:此文借鉴于

https://www.jianshu.com/p/c79f6a14f6c9

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。