JAVA从入门到精通之Swagger 与 Spring Boot REST API 集成详解
小职 2018-01-03 来源 :网络 阅读 808 评论 0

摘要:今天为大家讲解的是JAVA从入门到精通之Swagger 与 Spring Boot REST API 集成详解!Swagger(Swagger 2)是描述和记录REST API的一个规范。它指定了REST Web服务的格式,包括URL,资源,方法等。Swagger将从应用程序代码生成文档,并处理渲染部分。

今天为大家讲解的是JAVA从入门到精通之Swagger 与 Spring Boot REST API 集成详解


Swagger是什么

Swagger(Swagger 2)是描述和记录REST API的一个规范。它指定了REST Web服务的格式,包括URL,资源,方法等。Swagger将从应用程序代码生成文档,并处理渲染部分。

在这篇文章中,我会将Swagger 2文档集成到基于Spring Boot的REST Web服务中。我将使用Springfox实现来生成swagger文档。如果你想知道是如何运行/构建Spring Boot项目的,请参考我上一篇文章。

Springfox提供了两个依赖关系来生成API文档和Swagger UI。如果你不希望将Swagger UI集成到你的API中,则无需添加Swagger UI依赖关系。

<dependency>

<groupId>io.springfox</groupId>

<artifactId>springfox-swagger2</artifactId>

<version>2.7.0</version>

</dependency>

<dependency>

<groupId>io.springfox</groupId>

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

<version>2.7.0</version>

</dependency>

@ EnableSwagger2注解启用了Springfox Swagger在类中的支持。为了记录这个服务,Springfox使用了一个Docket类。Docket有助于配置要记录的服务,并通过名称等进行分组。后台是Springfox通过使用基于Spring配置的API语义,在运行时检查应用程序。换句话说,你必须创建一个使用Spring的@Configuration注解的Spring Java Configuration类。

在我的例子中,我会生成一个基于我添加的RestController类的swagger文档。

import springfox.documentation.spring.web.plugins.Docket;import springfox.documentation.swagger2.annotations.EnableSwagger2;


@Configuration

@EnableSwagger2

public class ApplicationConfig {


    @Bean

    public Docket api() {

        return new Docket(DocumentationType.SWAGGER_2)

                .select()

                .apis(RequestHandlerSelectors.basePackage("com.chandana.helloworld.controllers"))

                .paths(PathSelectors.any())

                .build();

    }

}

由于我添加了两个控制器,因此将分别对每个控制器相关的API进行分组(标记)。

JAVA从入门到精通之Swagger 与 Spring Boot REST API 集成详解

开箱即用,Springfox提供了5种断言,它们分别是any,none,withClassAnnotation,withMethodAnnotation和basePackage【译者注:参见springfox.documentation.builders. RequestHandlerSelectors类】


ApiInfo

Swagger提供了一些默认值,例如“API文档”,“通过联系人电子邮件创建”,“Apache 2.0”。当然你可以通过添加apiInfo(ApiInfo apiInfo)方法来更改这些默认值。ApiInfo类包含有关API的自定义信息。

@Bean

    public Docket api() {

        return new Docket(DocumentationType.SWAGGER_2)

                .apiInfo(getApiInfo())

                .select()

                .apis(RequestHandlerSelectors.basePackage("com.chandana.helloworld.controllers"))

                .paths(PathSelectors.any())

                .build();

    }


    private ApiInfo getApiInfo() {

        Contact contact = new Contact("Chandana Napagoda", "//blog.napagoda.com", "cnapagoda@gmail.com");

        return new ApiInfoBuilder()

                .title("Example Api Title")

                .description("Example Api Definition")

                .version("1.0.0")

                .license("Apache 2.0")

                .licenseUrl("//www.apache.org/licenses/LICENSE-2.0")

                .contact(contact)

                .build();

    }

一旦添加了ApiInfo,生成的文档看起来就像这样:

JAVA从入门到精通之Swagger 与 Spring Boot REST API 集成详解

Controller和POJO层文档

@Api注解用于说明每个控制器类(有点像类注释)。

@ApiOperation注解用于描述资源和方法。

@ApiResponse注解用于说明操作返回的其他响应值。例如:200 ok或202 accepted等

@ApiModelProperty注解用来描述POJO(Bean)类的属性(属性描述)。

添加上述注释后,最终生成的swagger文档如下所示:

JAVA从入门到精通之Swagger 与 Spring Boot REST API 集成详解

Spring RestController类:

package com.chandana.helloworld.controllers;

import com.chandana.helloworld.bean.Greeting;import io.swagger.annotations.Api;import io.swagger.annotations.ApiOperation;import io.swagger.annotations.ApiResponse;import io.swagger.annotations.ApiResponses;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RestController;

@RestController@RequestMapping("/api")@Api(value = "user", description = "Rest API for user operations", tags = "User API")public class HelloWorldController {


    @RequestMapping(value = "/hello/{name}", method = RequestMethod.GET, produces = "application/json")

    @ApiOperation(value = "Display greeting message to non-admin user", response = Greeting.class)

    @ApiResponses(value = {

            @ApiResponse(code = 200, message = "OK"),

            @ApiResponse(code = 404, message = "The resource not found")

    }

    )

    public Greeting message(@PathVariable String name) {

        Greeting msg = new Greeting(name, "Hello " + name);

        return msg;

    }

}

Greeting模型类:

package com.chandana.helloworld.bean;

import io.swagger.annotations.ApiModelProperty;

public class Greeting {


    @ApiModelProperty(notes = "Provided user name", required =true)

    private String player;


    @ApiModelProperty(notes = "The system generated greeting message" , readOnly =true)

    private String message;


    public Greeting(String player, String message) {

        this.player = player;

        this.message = message;

    }


    public String getPlayer() {

        return player;

    }


    public void setPlayer(String player) {

        this.player = player;

    }


    public String getMessage() {

        return message;

    }


    public void setMessage(String message) {

        this.message = message;

    }

}

AppConfig类:

package com.chandana.helloworld.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

@EnableSwagger2public class ApplicationConfig {


    @Bean

    public Docket api() {

        return new Docket(DocumentationType.SWAGGER_2)

                .apiInfo(getApiInfo())

                .select()

                .apis(RequestHandlerSelectors.basePackage("com.chandana.helloworld.controllers"))

                .paths(PathSelectors.any())

                .build();

    }


    private ApiInfo getApiInfo() {

        Contact contact = new Contact("Chandana Napagoda", "//blog.napagoda.com", "cnapagoda@gmail.com");

        return new ApiInfoBuilder()

                .title("Example Api Title")

                .description("Example Api Definition")

                .version("1.0.0")

                .license("Apache 2.0")

                .licenseUrl("//www.apache.org/licenses/LICENSE-2.0")

                .contact(contact)

                .build();

    }

}

你也可以从我的GitHub repo 下载  Swagger Spring Boot Project 源代码。


译者注:

1.如果你对Spring Boot不是很熟悉,建议先fork下源码,因为有些依赖文中没有提到。

2.启动Spring Boot后,在浏览器中输入:127.0.0.1:8080/swagger-ui.html即可查看生成的文档信息。

在生成的文档页面中,可以输入参数,点击“Try it out!”即可进行接口测试,有点类似于Postman的功能。


以上,关于Java的内容讲解完毕,欢迎大家继续关注!更多关于Java的干货请关注职坐标Java频道!

本文由 @小职 发布于职坐标。未经许可,禁止转载。
喜欢 | 1 不喜欢 | 0
看完这篇文章有何感觉?已经有1人表态,100%的人喜欢 快给朋友分享吧~
评论(0)
后参与评论

您输入的评论内容中包含违禁敏感词

我知道了

助您圆梦职场 匹配合适岗位
验证码手机号,获得海同独家IT培训资料
选择就业方向:
人工智能物联网
大数据开发/分析
人工智能Python
Java全栈开发
WEB前端+H5

请输入正确的手机号码

请输入正确的验证码

获取验证码

您今天的短信下发次数太多了,明天再试试吧!

提交

我们会在第一时间安排职业规划师联系您!

您也可以联系我们的职业规划师咨询:

小职老师的微信号:z_zhizuobiao
小职老师的微信号:z_zhizuobiao

版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
 沪公网安备 31011502005948号    

©2015 www.zhizuobiao.com All Rights Reserved

208小时内训课程