Swagger 与 Spring Boot REST API 集成详解
本文由码农网 – Pansanday原创翻译,转载请看清文末的转载要求,欢迎参与我们的付费投稿计划!
在上一篇文章中,我谈到了使用Spring Boot创建RESTFul服务的经验。当创建一个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依赖关系。
io.springfox springfox-swagger2 2.7.0
io.springfox springfox-swagger-ui 2.7.0
@ 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进行分组(标记)。
开箱即用,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", "http://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("http://www.apache.org/licenses/LICENSE-2.0")
.contact(contact)
.build();
}
一旦添加了ApiInfo,生成的文档看起来就像这样:
Controller和POJO层文档
@Api注解用于说明每个控制器类(有点像类注释)。
@ApiOperation注解用于描述资源和方法。
@ApiResponse注解用于说明操作返回的其他响应值。例如:200 ok或202 accepted等
@ApiModelProperty注解用来描述POJO(Bean)类的属性(属性描述)。
添加上述注释后,最终生成的swagger文档如下所示:
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
@EnableSwagger2
public 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", "http://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("http://www.apache.org/licenses/LICENSE-2.0")
.contact(contact)
.build();
}
}
你也可以从我的GitHub repo 下载 Swagger Spring Boot Project 源代码。
译者注:
- 如果你对Spring Boot不是很熟悉,建议先fork下源码,因为有些依赖文中没有提到。
- 启动Spring Boot后,在浏览器中输入:127.0.0.1:8080/swagger-ui.html即可查看生成的文档信息。
在生成的文档页面中,可以输入参数,点击“Try it out!”即可进行接口测试,有点类似于Postman的功能。
译文链接:http://www.codeceo.com/article/swagger-spring-boot-rest-api.html
英文原文:Integrating Swagger with Spring Boot REST API
翻译作者:码农网 – Pansanday
[ 转载必须在正文中标注并保留原文链接、译文链接和译者等信息。]
推荐阅读
-
4个理由告诉你Java为何排行第一
本文由码农网 –单劼原创翻译,转载请看清文末的转载要求,欢迎参与我们的付费投稿计划!Java已经有20年的历史了,甚...
-
写给精明Java开发者的测试技巧
我们都会为我们的代码编写测试,不是吗?毫无疑问,我知道这个问题的答案可能会从“当然,但你知道怎样才能避免写测试吗?”到“必须...
-
Java 微服务框架 Redkale 入门介绍
Redkale功能Redkale虽然只有1.xM大小,但是麻雀虽小五脏俱全。既可作为服务器使用,也可当工具包使用。作为独立的工...
-
Java内存管理原理及内存区域详解
一、概述Java虚拟机在执行Java程序的过程中会把它所管理的内存划分为若干不同的数据区域,这些区域都有各自的用途以及创建和销毁...
-
2015年Java开发岗位面试题归类
下面是我自己收集整理的Java岗位今天面经遇到的面试题,可以用它来好好准备面试。一、Java基础1.String...
-
Java 虚拟机类加载机制和字节码执行引擎
引言我们知道java代码编译后生成的是字节码,那虚拟机是如何加载这些class字节码文件的呢?加载之后又是如何进行方法调用的呢?...
-
Java常量池理解与总结
一.相关概念什么是常量用final修饰的成员变量表示常量,值一旦给定就无法改变!final修饰的变量有三种:静态...
-
Java 实现线程死锁
概述春节的时候去面试了一家公司,笔试题里面有一道是使用简单的代码实现线程的‘死锁’,当时没有想到这道题考的是Sync...
-
Java:过去、未来的互联网编程之王
Java对你而言是什么?一门你大学里学过的语言?一个IT行业的通用语言?你相信Java已经为下一次互联网爆炸做好了准备么?Java...
-
20个高级Java面试题汇总
本文由码农网 –小峰原创翻译,转载请看清文末的转载要求,欢迎参与我们的付费投稿计划!这是一个高级Java面试系列题中...
