SpringBoot——Swagger2 接口规范

这篇具有很好参考价值的文章主要介绍了SpringBoot——Swagger2 接口规范。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

优质博文:IT-BLOG-CN

如今,REST和微服务已经有了很大的发展势头。但是,REST规范中并没有提供一种规范来编写我们的对外REST接口API文档。每个人都在用自己的方式记录api文档,因此没有一种标准规范能够让我们很容易的理解和使用该接口。我们需要一个共同的规范和统一的工具来解决文档的难易理解文档的混乱格式。Swagger(在谷歌、IBM、微软等公司的支持下)做了一个公共的文档风格来填补上述问题。在本博客中,我们将会学习怎么使用SwaggerSwagger2注解去生成REST API文档。

Swagger(现在是“开放 API计划”)是一种规范和框架,它使用一种人人都能理解的通用语言来描述REST API。还有其他一些可用的框架,比如RAML、求和等等,但是 Swagger是最受欢迎的。它提供了人类可读和机器可读的文档格式。它提供了JSONUI支持。JSON可以用作机器可读的格式,而 Swagger-UI是用于可视化的,通过浏览api文档,人们很容易理解它。

一、添加 Swagger2 的 maven依赖

打开项目中的 pom.xml文件,添加以下两个 swagger依赖。springfox-swagger2 、springfox-swagger-ui。

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

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

实际上,Swagger的 API有两种类型,并在不同的工件中维护。今天我们将使用 springfox,因为这个版本可以很好地适应任何基于 spring的配置。我们还可以很容易地尝试其他配置,这应该提供相同的功能——配置中没有任何变化。

二、添加 Swagger2配置

使用 Java config的方式添加配置。为了帮助你理解这个配置,我在代码中写了相关的注释:

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.WebMvcConfigurerAdapter;
import com.google.common.base.Predicates;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class Swagger2UiConfiguration extends WebMvcConfigurerAdapter
{
    @Bean
    public Docket api() {
        // @formatter:off
        //将控制器注册到 swagger
        //还配置了Swagger 容器
        return new Docket(DocumentationType.SWAGGER_2).select()
                 .apiInfo(apiInfo())
                 .select()
                 .apis(RequestHandlerSelectors.any())
                 //扫描 controller所有包
                 .apis(Predicates.not(RequestHandlerSelectors.basePackage("org.springframework.boot")))
                 .paths(PathSelectors.any())
                 .paths(PathSelectors.ant("/swagger2-demo"))
                 .build();
        // @formatter:on
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry)
    {
        //为可视化文档启用swagger ui部件
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}

通过 api()方法返回 Docket,调用以下方法:
【1】apiInfo()方法中可以添加 api文档的基本信息(具体类型查看文档);
【2】select()方法返回 ApiSelectorBuilder实例,用于过滤哪些 api需要显示;
【3】apis()方法中填写项目中 Controller类存放的路径;

最后 build()建立 Docket。

三、验证 Swagger2的 JSON格式文档

在application.yml中配置服务名为:swagger2-demo

server.contextPath=/swagger2-demo

maven构建并启动服务器。打开链接,会生成一个JSON格式的文档。这并不是那么容易理解,实际上Swagger已经提供该文档在其他第三方工具中使用,例如当今流行的 API管理工具,它提供了API网关、API缓存、API文档等功能。

SpringBoot——Swagger2 接口规范,SpringBoot,spring boot,后端,java,职场和发展,spring,maven,swagger

四、验证 Swagger2 UI文档

打开链接 在浏览器中来查看Swagger UI文档;

SpringBoot——Swagger2 接口规范,SpringBoot,spring boot,后端,java,职场和发展,spring,maven,swagger

五、Swagger2 注解的使用

默认生成的 API文档很好,但是它们缺乏详细的 API级别信息。Swagger提供了一些注释,可以将这些详细信息添加到 api中。如。@Api我们可以添加这个注解在 Controller上,去添加一个基本的 Controller说明。

@Api(value = "Swagger2DemoRestController", description = "REST APIs related to Student Entity!!!!")
@RestController
public class Swagger2DemoRestController {
    //...
}

@ApiOperation and @ApiResponses我们添加这个注解到任何 Controller的 rest方法上来给方法添加基本的描述。例如:

@ApiOperation(value = "Get list of Students in the System ", response = Iterable.class, tags = "getStudents")
@ApiResponses(value = {
            @ApiResponse(code = 200, message = "Success|OK"),
            @ApiResponse(code = 401, message = "not authorized!"),
            @ApiResponse(code = 403, message = "forbidden!!!"),
            @ApiResponse(code = 404, message = "not found!!!") })

@RequestMapping(value = "/getStudents")
public List<Student> getStudents() {
    return students;
}

在这里,我们可以向方法中添加标签,来在 swagger-ui中添加一些分组。@ApiModelProperty这个注解用来在数据模型对象中的属性上添加一些描述,会在 Swagger UI中展示模型的属性。例如:

@ApiModelProperty(notes = "Name of the Student",name="name",required=true,value="test name")
private String name;

Controller 和 Model 类添加了swagger2注解之后,代码清单:Swagger2DemoRestController.java

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.springbootswagger2.model.Student;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

@Api(value = "Swagger2DemoRestController", description = "REST Apis related to Student Entity!!!!")
@RestController
public class Swagger2DemoRestController {

    List<Student> students = new ArrayList<Student>();
    {
        students.add(new Student("Sajal", "IV", "India"));
        students.add(new Student("Lokesh", "V", "India"));
        students.add(new Student("Kajal", "III", "USA"));
        students.add(new Student("Sukesh", "VI", "USA"));
    }

    @ApiOperation(value = "Get list of Students in the System ", response = Iterable.class, tags = "getStudents")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "Suceess|OK"),
            @ApiResponse(code = 401, message = "not authorized!"),
            @ApiResponse(code = 403, message = "forbidden!!!"),
            @ApiResponse(code = 404, message = "not found!!!") })

    @RequestMapping(value = "/getStudents")
    public List<Student> getStudents() {
        return students;
    }

    @ApiOperation(value = "Get specific Student in the System ", response = Student.class, tags = "getStudent")
    @RequestMapping(value = "/getStudent/{name}")
    public Student getStudent(@PathVariable(value = "name") String name) {
        return students.stream().filter(x -> x.getName().equalsIgnoreCase(name)).collect(Collectors.toList()).get(0);
    }

    @ApiOperation(value = "Get specific Student By Country in the System ", response = Student.class, tags = "getStudentByCountry")
    @RequestMapping(value = "/getStudentByCountry/{country}")
    public List<Student> getStudentByCountry(@PathVariable(value = "country") String country) {
        System.out.println("Searching Student in country : " + country);
        List<Student> studentsByCountry = students.stream().filter(x -> x.getCountry().equalsIgnoreCase(country))
                .collect(Collectors.toList());
        System.out.println(studentsByCountry);
        return studentsByCountry;
    }

    // @ApiOperation(value = "Get specific Student By Class in the System ",response = Student.class,tags="getStudentByClass")
    @RequestMapping(value = "/getStudentByClass/{cls}")
    public List<Student> getStudentByClass(@PathVariable(value = "cls") String cls) {
        return students.stream().filter(x -> x.getCls().equalsIgnoreCase(cls)).collect(Collectors.toList());
    }
}

Student.java 实体类

import io.swagger.annotations.ApiModelProperty;

public class Student
{
    @ApiModelProperty(notes = "Name of the Student",name="name",required=true,value="test name")
    private String name;

    @ApiModelProperty(notes = "Class of the Student",name="cls",required=true,value="test class")
    private String cls;

    @ApiModelProperty(notes = "Country of the Student",name="country",required=true,value="test country")
    private String country;

    public Student(String name, String cls, String country) {
        super();
        this.name = name;
        this.cls = cls;
        this.country = country;
    }

    public String getName() {
        return name;
    }

    public String getCls() {
        return cls;
    }

    public String getCountry() {
        return country;
    }

    @Override
    public String toString() {
        return "Student [name=" + name + ", cls=" + cls + ", country=" + country + "]";
    }
}

六、swagger-ui 展示

现在,当我们的 REST api得到适当的注释时,让我们看看最终的输出。打开http://localhost:8080/swagger2-demo/swagger-ui。在浏览器中查看 Swagger ui文档。

SpringBoot——Swagger2 接口规范,SpringBoot,spring boot,后端,java,职场和发展,spring,maven,swagger文章来源地址https://www.toymoban.com/news/detail-756349.html

到了这里,关于SpringBoot——Swagger2 接口规范的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 微服务接口工具Swagger2

    ##1、什么是Swagger? 核心功能 生成接口说明文档 生成接口测试工具 1)、添加依赖 2)、增加Swagger配置类 如上代码所示,通过  @Configuration  注解,让 Spring 加载该配置类。再通过  @EnableSwagger2  注解来启用Swagger2。成员方法  createRestApi  函数创建  Docket  的Bean之后, apiInfo

    2024年01月17日
    浏览(31)
  • Java技术-接口文档-Swagger2&Swagger3&接口文档UI整合

    目录 一、Swagger2完整用法 1.POM依赖 2.接口类 3.实现类 4.托管静态资源 5.接口文档配置 6.生产环境关闭接口文档 7.Swagger3页面效果 二、Swagger3完整用法 三、Swagger整合Knife4jUi 1.POM依赖 2.接口类 3.实现类 4.托管静态资源 5.接口文档配置 6.生产环境关闭接口文档 四、注释和参数讲解

    2024年02月16日
    浏览(36)
  • 接口工具Swagger2和Swagger-UI的使用

    目录 一、为什么需要接口可视化工具? 二、Swagger-UI介绍: 1、在项目的pom文件中导入swagger2的依赖 2、下载Swagger-UI项目 3、引入Swagger-UI 4、编写配置文件 第一种: 第二种: 5、访问api文档页面 6、如果访问失败,则进行第六步,如果访问成功,就不用操作了。 我们的项目通常

    2024年02月08日
    浏览(36)
  • Springboot+swagger2

    1.swagger配置 2.请求路径  http://localhost:8006/swagger2/swagger-ui.html 3.Swagger2 注解整理  4.代码示例          

    2024年02月09日
    浏览(28)
  • SpringBoot整合Swagger2

    在团队开发中,一个好的 API 文档不但可以减少大量的沟通成本,还可以帮助一位新人快速上手业务。传统的做法是由开发人员创建一份 RESTful API 文档来记录所有的接口细节,并在程序员之间代代相传。这种做法存在以下几个问题: 1)API 接口众多,细节复杂,需要考虑不同

    2023年04月16日
    浏览(29)
  • SpringBoot 整合Swagger2

    Swagger是一套开源工具和规范,用于设计、构建和文档化 RESTful Web 服务。它允许开发人员定义API的各个方面,并生成易于理解的API文档和交互式API探索界面。同时,Swagger还提供代码生成工具,可自动生成与API交互的客户端和服务器端代码,提高开发效率。 官网:https://swagge

    2024年04月27日
    浏览(24)
  • springboot 2.7版本整合swagger2代码实现

    1.导入swagger2依赖 2.添加swagger配置类 3.启动项目就这么easy  4.easy个屁,报错了,抛出了异常信息:   Failed to start bean \\\'documentationPluginsBootstrapper\\\'; nested exception is java.lang.NullPointerException: Cannot invoke \\\"org.springframework.web.servlet.mvc.condition.PatternsRequestCondition.getPatterns() 5.发现这是sp

    2024年02月09日
    浏览(29)
  • SpringBoot项目中使用Swagger2及注解解释(详细)

    SpringBoot项目中使用Swagger2及注解解释 一、导入Swagger坐标依赖 其中版本最常用2.9.2 二、在spring启动类添加注解@EnableSwagger2 @EnableSwagger2是springfox提供的一个注解,代表swagger2相关技术开启。会扫描当前类所在包,及子包中所有类型的swagger相关注解,做swagger文档的定制 三、启动

    2023年04月18日
    浏览(73)
  • Springboot整合Swagger2后访问swagger-ui.html 404报错

    在spring boot项目中配置Swagger2,配置好了但是访问确实404,SwaggerConfig中的注入方法也执行了还是访问不到页面。究其原因是MVC没有找到swagger-ui包中的swagger-ui.html文件和css样式、js等文件。 解决⽅案: ⽅案1. 降低Swagger2的使用版本 ⽅案2. 使⽤配置⼀下+swagger-ui.html+指定的css⽬录

    2024年02月11日
    浏览(28)
  • Spring Boot入门(16):Spring Boot 整合 Swagger-UI 实现在线API接口文档 | 超级详细,建议收藏

            在现代化的软件开发中,API接口文档的编写和管理是非常重要的一环。而Swagger-UI作为一款优秀的API文档生成工具,可以帮助开发者轻松地生成并管理API接口文档,提高开发效率和代码质量。在本文中,我们将介绍如何使用Spring Boot框架和Swagger-UI工具实现在线API接

    2024年02月16日
    浏览(42)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包