16、springcloud整合Swagger2构建Restful服务的APIs

简介: 比如说代码改了,但是接口文档还没来得及修改等问题,而Swagger2则给我们提供了一套完美的解决方案,下面来看看Swagger2是如何来解决这个问题的。

Spring Cloud将服务注册到了Eureka上,可以从EurekaUI界面中,看到有哪些服务已经注册到了Eureka Server但是如果想查看当前服务提供了哪些RESTful接口方法的话,就无Eureka Server获取了,而传统的方法是梳理一个接口文档来供开发人员之间来进行交流这种情况下经常会造成文档和代码的不一致性,比如说代码改了,但是接口文档来得及修改等问题,而Swagger2则给我们提供了一套完美的解决方案,下面来看看Swagger2是如何来解决这个问题的。

 

1、 新建项目sc-swagger2,对应的pom.xml文件


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>spring-cloud</groupId>
<artifactId>sc-swagger2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>sc-swagger2</name>
<url>http://maven.apache.org</url>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
</parent>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Finchley.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>


2、 新建springboot启动类


package sc.swagger2;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Swagger2Application {
public static void main(String[] args) {
SpringApplication.run(Swagger2Application.class, args);
}
}


3、 新建Swagger2配置类


package sc.swagger2.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 Swagger2Config {
@Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("sc.swagger2"))
                .paths(PathSelectors.any())
                .build();
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Spring Boot中使用Swagger2构建RESTful APIs")
                .description("更多Spring Boot相关文章请关注: JAVA乐园  公众号")
                .termsOfServiceUrl("https://edu.csdn.net/lecturer/995")
                .contact(new Contact("huangjinjin", //
                 "https://edu.csdn.net/lecturer/995",//
                 "happyhuangjinjin@sina.com"))
                .version("1.0")
                .build();
    }
}


4、 新建一个模拟的Controller


package sc.swagger2.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import sc.swagger2.model.User;
@Api(value="用户管理")
@Controller
public class UserController {
@ApiResponses({ @ApiResponse(code = 000000, message = "操作成功"),
@ApiResponse(code = 000001, message = "服务器内部异常") })
@GetMapping(value = "/feign/user/getUser/{id}")
@ResponseBody
@ApiOperation(value = "获取根据Id用户信息",response = User.class)
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long",example="100")
public Map<String, Object> getUser(@PathVariable Long id) {
Map<String, Object> result = new HashMap<String, Object>();
result.put("code", "000000");
result.put("msg", "success");
User u = new User();
u.setId(1L);
u.setAge(23);
u.setUserName("huangjinjin");
u.setPosition("cto");
result.put("body", u);
return result;
}
@ApiResponses({ @ApiResponse(code = 000000, message = "操作成功"),
@ApiResponse(code = 000001, message = "服务器内部异常") })
@RequestMapping(value = "/feign/user/listUser", method = RequestMethod.GET)
@ResponseBody
@ApiOperation(value = "获取用户列表")
public Map<String, Object> listUser() {
Map<String, Object> result = new HashMap<String, Object>();
result.put("code", "000000");
result.put("msg", "success");
User u = new User();
u.setId(1L);
u.setAge(23);
u.setUserName("huangjinjin");
u.setPosition("cto");
List<User> list = new ArrayList<User>();
list.add(u);
result.put("body", list);
return result;
}
@ApiResponses({ @ApiResponse(code = 000000, message = "操作成功"),
@ApiResponse(code = 000001, message = "服务器内部异常") })
@PostMapping(value = "/feign/user/addUser")
@ResponseBody
@ApiOperation(value = "添加用户", notes = "根据User对象创建用户")
@ApiImplicitParams({ @ApiImplicitParam(name = "userName", value = "用户名", required = true, dataType = "String"),
@ApiImplicitParam(name = "age", value = "年龄", required = true, dataType = "String"),
@ApiImplicitParam(name = "position", value = "职位", required = true, dataType = "String"),
@ApiImplicitParam(name = "id", value = "用户ID", required = false, dataType = "Long",example="100")})
public Map<String, Object> addUser(User user) {
Map<String, Object> result = new HashMap<String, Object>();
result.put("code", "000000");
result.put("msg", "success");
result.put("body", 1);
return result;
}
@ApiResponses({ @ApiResponse(code = 000000, message = "操作成功"),
@ApiResponse(code = 000001, message = "服务器内部异常") })
@ApiOperation(value = "更新用户")
@PutMapping(value = "/feign/user/updateUser")
@ResponseBody
@ApiImplicitParams({ @ApiImplicitParam(name = "userName", value = "用户名", required = true, dataType = "String"),
@ApiImplicitParam(name = "age", value = "年龄", required = true, dataType = "String"),
@ApiImplicitParam(name = "position", value = "职位", required = true, dataType = "String"),
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long", example="100")})
public Map<String, Object> updateUser(User user) {
Map<String, Object> result = new HashMap<String, Object>();
result.put("code", "000000");
result.put("msg", "success");
result.put("body", 1);
return result;
}
@ApiResponses({ @ApiResponse(code = 000000, message = "操作成功"),
@ApiResponse(code = 000001, message = "服务器内部异常") })
@DeleteMapping(value = "/feign/user/deleteUser/{id}")
@ResponseBody
@ApiOperation(value = "删除用户")
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long",example="100")
public Map<String, Object> deleteUser(@PathVariable Long id) {
Map<String, Object> result = new HashMap<String, Object>();
result.put("code", "000000");
result.put("msg", "success");
result.put("body", 1);
return result;
}
}


5、 新建User模型类


package sc.swagger2.model;
import java.io.Serializable;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel
public class User implements Serializable {
private static final long serialVersionUID = 4639927446947303736L;
@ApiModelProperty(name="id", dataType="Long", value="主键ID")
private Long id;
@ApiModelProperty(name="userName", dataType="String", value="姓名", required=true)
private String userName;
@ApiModelProperty(name="age", dataType="String", value="年龄", required=true)
private Integer age;
@ApiModelProperty(name="position", dataType="String", value="职位")
private String position;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}


6、 启动sc-swagger2项目,并验证是否启动成功


方式一:查看日志


微信图片_20220501182610.png


方式二:访问地址


http://127.0.0.1:9092/swagger-ui.html


微信图片_20220501182614.png


或者访问http://localhost:9092/v2/api-docs

 

微信图片_20220501182618.png


7、 在界面http://127.0.0.1:9092/swagger-ui.html点击【user-controller】可以看到所有的接口,同时也可以在界面上进行接口调用调试


微信图片_20220501182622.png


https://gitee.com/hjj520/spring-cloud-2.x








相关文章
|
2月前
|
JSON JavaScript 前端开发
深入浅出Node.js:从零开始构建RESTful API
在数字化时代的浪潮中,后端开发作为连接用户与数据的桥梁,扮演着至关重要的角色。本文将引导您步入Node.js的奇妙世界,通过实践操作,掌握如何使用这一强大的JavaScript运行时环境构建高效、可扩展的RESTful API。我们将一同探索Express框架的使用,学习如何设计API端点,处理数据请求,并实现身份验证机制,最终部署我们的成果到云服务器上。无论您是初学者还是有一定基础的开发者,这篇文章都将为您打开一扇通往后端开发深层知识的大门。
71 12
|
3月前
|
JSON 缓存 测试技术
构建高效RESTful API的后端实践指南####
本文将深入探讨如何设计并实现一个高效、可扩展且易于维护的RESTful API。不同于传统的摘要概述,本节将直接以行动指南的形式,列出构建RESTful API时必须遵循的核心原则与最佳实践,旨在为开发者提供一套直接可行的实施框架,快速提升API设计与开发能力。 ####
|
3月前
|
安全 测试技术 API
构建高效RESTful API:后端开发的艺术与实践####
在现代软件开发的浩瀚星空中,RESTful API如同一座桥梁,连接着前端世界的绚丽多彩与后端逻辑的深邃复杂。本文旨在探讨如何精心打造一款既高效又易于维护的RESTful API,通过深入浅出的方式,剖析其设计原则、实现技巧及最佳实践,为后端开发者提供一份实用的指南。我们不深入晦涩的理论,只聚焦于那些能够即刻提升API品质与开发效率的关键点,让你的API在众多服务中脱颖而出。 ####
45 0
|
3月前
|
监控 安全 API
深入浅出:构建高效RESTful API的最佳实践
在数字化时代,API已成为连接不同软件和服务的桥梁。本文将带你深入了解如何设计和维护一个高效、可扩展且安全的RESTful API。我们将从基础概念出发,逐步深入到高级技巧,让你能够掌握创建优质API的关键要素。无论你是初学者还是有经验的开发者,这篇文章都将为你提供实用的指导和启示。让我们一起探索API设计的奥秘,打造出色的后端服务吧!
|
3月前
|
JavaScript NoSQL API
深入浅出Node.js:从零开始构建RESTful API
在数字化时代的浪潮中,后端开发如同一座灯塔,指引着数据的海洋。本文将带你航行在Node.js的海域,探索如何从一张白纸到完成一个功能完备的RESTful API。我们将一起学习如何搭建开发环境、设计API结构、处理数据请求与响应,以及实现数据库交互。准备好了吗?启航吧!
|
1月前
|
人工智能 安全 Java
AI 时代:从 Spring Cloud Alibaba 到 Spring AI Alibaba
本次分享由阿里云智能集团云原生微服务技术负责人李艳林主讲,主题为“AI时代:从Spring Cloud Alibaba到Spring AI Alibaba”。内容涵盖应用架构演进、AI agent框架发展趋势及Spring AI Alibaba的重磅发布。分享介绍了AI原生架构与传统架构的融合,强调了API优先、事件驱动和AI运维的重要性。同时,详细解析了Spring AI Alibaba的三层抽象设计,包括模型支持、工作流智能体编排及生产可用性构建能力,确保安全合规、高效部署与可观测性。最后,结合实际案例展示了如何利用私域数据优化AI应用,提升业务价值。
141 4
|
1月前
|
人工智能 自然语言处理 Java
Spring Cloud Alibaba AI 入门与实践
本文将介绍 Spring Cloud Alibaba AI 的基本概念、主要特性和功能,并演示如何完成一个在线聊天和在线画图的 AI 应用。
357 7
|
2月前
|
存储 SpringCloudAlibaba Java
【SpringCloud Alibaba系列】一文全面解析Zookeeper安装、常用命令、JavaAPI操作、Watch事件监听、分布式锁、集群搭建、核心理论
一文全面解析Zookeeper安装、常用命令、JavaAPI操作、Watch事件监听、分布式锁、集群搭建、核心理论。
【SpringCloud Alibaba系列】一文全面解析Zookeeper安装、常用命令、JavaAPI操作、Watch事件监听、分布式锁、集群搭建、核心理论
|
2月前
|
SpringCloudAlibaba 负载均衡 Dubbo
【SpringCloud Alibaba系列】Dubbo高级特性篇
本章我们介绍Dubbo的常用高级特性,包括序列化、地址缓存、超时与重试机制、多版本、负载均衡。集群容错、服务降级等。
【SpringCloud Alibaba系列】Dubbo高级特性篇
|
2月前
|
SpringCloudAlibaba JavaScript Dubbo
【SpringCloud Alibaba系列】Dubbo dubbo-admin安装教程篇
本文介绍了 Dubbo-Admin 的安装和使用步骤。Dubbo-Admin 是一个前后端分离的项目,前端基于 Vue,后端基于 Spring Boot。安装前需确保开发环境(Windows 10)已安装 JDK、Maven 和 Node.js,并在 Linux CentOS 7 上部署 Zookeeper 作为注册中心。
【SpringCloud Alibaba系列】Dubbo dubbo-admin安装教程篇