Spring Boot集成Swagger2

本文介绍了如何在Spring Boot 2.1.0项目中集成Swagger2,实现API接口的文档生成和测试。通过添加相关依赖、编写Swagger配置、在Controller和Model中添加注解,最后在浏览器输入http://localhost:8080/swagger-ui.html即可查看和测试接口。注意在使用Swagger2.9.0时可能会遇到数据类型转换错误,可以通过更新jar包来解决。
摘要由CSDN通过智能技术生成

前言:目前互联网开发市场都流行前后台真正的分离,后台提供数据API接口,前台负责请求数据并渲染。那么我们程序猿们在编写接口的时候,最不方便之处就是写完接口后需要进行文档的编写以及接口的测试。今天就介绍一款将接口文档编写和测试合并一起的集大成者Swagger,也是目前很多企业再用的一个API管理工具。此DEMO的开发环境是:MAVEN + Spring Boot 2.1.0 + JDK8 + Swagger2.9.2

1、快速构建Spring Boot项目

在https://start.spring.io/中选择Maven构建Java项目,然后选用Spring Boot2.1.0版本,Group是com.mage,Artifact是swagger_restful,Dependencies选择web,这样就能快速构建一个基于Spring Boot的web项目了。如下图:

项目构建

项目构建

2、使用IDEA打开项目

解压swagger_restful.zip,然后使用idea导入项目,并执行SwaggerRestfulApplication.java,不报错说明项目构建成功

启动项目

启动项目

3、pom导入swagger2的依赖jar包

<!-- 用于JSON API文档的生成-->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>

<!--用于文档界面展示-->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

其中springfox-swagger2这个jar包是用于JSON API文档的生成,springfox-swagger-ui用于API文档界面生成,其他版本请参考:https://mvnrepository.com/artifact/io.springfox/springfox-swagger2和https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui

5、编写测试的Controller和Model(TestController和Test)

编写一个Test的数据模型

package com.mage.swagger_restful.model;

public class Test {
    private Integer id;
    private String content;
    private Integer isValid;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public Integer getIsValid() {
        return isValid;
    }

    public void setIsValid(Integer isValid) {
        this.isValid = isValid;
    }
}

基于Restful规则,编写

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值