前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Spring Boot中使用Swagger2构建强大的RESTful API文档

Spring Boot中使用Swagger2构建强大的RESTful API文档

作者头像
itliusir
发布2018-05-21 16:35:23
1.1K0
发布2018-05-21 16:35:23
举报
文章被收录于专栏:刘君君刘君君

摘要:Swagger2,它可以轻松的整合到Spring Boot中,并与Spring MVC程序配合组织出强大RESTful API文档。它既可以减少我们创建文档的工作量,同时说明内容又整合入实现代码中,让维护文档和修改代码整合为一体,可以让我们在修改代码逻辑的同时方便的修改文档说明。另外Swagger2也提供了强大的页面测试功能来调试每个RESTful API。

正文:

具体效果如下图所示:

下面来具体介绍,如何在Spring Boot中使用Swagger2。

添加Swagger2依赖

在pom.xml中加入Swagger2的依赖

<!-- Swagger2的依赖 --><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>

创建Swagger2配置类

在Application.java同级创建Swagger2的配置类Swagger2。

@Configuration@EnableSwagger2public class Swagger2 { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.ysstech.micro.web")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("Spring Boot中使用Swagger2构建RESTful APIs") .contact("ysstech") .version("1.0") .build(); }}

如上代码所示,通过@Configuration注解,让Spring来加载该类配置。再通过@EnableSwagger2注解来启用Swagger2。

再通过createRestApi函数创建Docket的Bean之后,apiInfo()用来创建该Api的基本信息(这些基本信息会展现在文档页面中)。select()函数返回一个ApiSelectorBuilder实例用来控制哪些接口暴露给Swagger来展现,本例采用指定扫描的包路径来定义,Swagger会扫描该包下所有Controller定义的API,并产生文档内容(除了被@ApiIgnore指定的请求)。

添加文档内容

在完成了上述配置后,其实已经可以生产文档内容,但是这样的文档主要针对请求本身,而描述主要来源于函数等命名产生,对用户并不友好,我们通常需要自己增加一些说明来丰富文档内容。如下所示,我们通过@ApiOperation注解来给API增加说明、通过@ApiImplicitParams、@ApiImplicitParam注解来给参数增加说明。

@RestController @RequestMapping(value="/user")/** * Spring Boot:约定优于配置 * Spring Boot构建RESTful API * */public class UserController { @Autowired UsersService UsersService=null; @ApiOperation(value="获取用户列表",notes="") @RequestMapping(value="/", method=RequestMethod.GET) public ResponseInfo getUserList() throws Exception{ // 处理"/users/"的GET请求,用来获取用户列表 ResponseInfo resInfo = new ResponseInfo(); List<Users> list = new ArrayList<Users>(); resInfo.setResponseInfo(list); return resInfo; } @ApiOperation(value="获取用户详细信息",notes="根据url的id来获取用户详细信息") @ApiImplicitParam(name="id",value="用户ID",required=true,dataType="int",paramType="path") @RequestMapping(value="/{id}", method=RequestMethod.GET) public ResponseInfo getUser(@PathVariable int id) throws Exception{ ResponseInfo resInfo = new ResponseInfo(); //List<Users> list = new ArrayList<Users>(); Users user =UsersService.selectByPrimaryKey(id); resInfo.setResponseInfo(user); return resInfo; } @ApiOperation(value="创建用户",notes="根据User对象创建用户") @ApiImplicitParam(name="user",value="用户详细实体user",required=true) @RequestMapping(value="/", method=RequestMethod.POST) public ResponseInfo postUser(@RequestBody Users user) throws Exception{ // 处理"/users/"的POST请求,用来创建User ResponseInfo resInfo = new ResponseInfo(); UsersService.insert(user); return resInfo; } @ApiOperation(value="更新用户详细信息", notes="根据url的id来指定更新对象,并根据传过来的user信息来更新用户详细信息") @ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "int",paramType="path"), @ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User") }) @RequestMapping(value="/{id}", method=RequestMethod.PUT) public ResponseInfo putUser(@PathVariable int id, @RequestBody Users user) throws Exception{ // 处理"/users/{id}"的PUT请求,用来更新User信息 ResponseInfo resInfo = new ResponseInfo(); List<Users> list = new ArrayList<Users>(); Users user1 = list.get(id); user1.setAge(user.getAge()); user1.setId(user.getId()); user1.setName(user.getName()); resInfo.setResponseInfo(list); return resInfo; } @ApiOperation(value="删除用户", notes="根据url的id来指定删除对象") @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "int",paramType="path") @RequestMapping(value="/{id}", method=RequestMethod.DELETE) public ResponseInfo deleteUser(@PathVariable int id) throws Exception{ // 处理"/users/{id}"的DELETE请求,用来删除User ResponseInfo resInfo = new ResponseInfo(); List<Users> list = new ArrayList<Users>(); list.remove(id); resInfo.setResponseInfo(list); return resInfo; } }

完成上述代码添加上,启动Spring Boot程序,访问:http://localhost:8088/demojar/swagger-ui.html(加的有根目录demojar) 。就能看到前文所展示的RESTful API的页面。我们可以再点开具体的API请求,以POST类型的/users请求为例,可找到上述代码中我们配置的Notes信息以及参数user的描述信息,如下图所示。

API文档访问与调试

在上图请求的页面中,我们看到user的Value是个输入框?是的,Swagger除了查看接口功能外,还提供了调试测试功能,我们可以点击上图中右侧的Model Schema(黄色区域:它指明了User的数据结构),此时Value中就有了user对象的模板,我们只需要稍适修改,点击下方“Try it out!”按钮,即可完成了一次请求调用!

此时,你也可以通过几个GET请求来验证之前的POST请求是否正确。

相比为这些接口编写文档的工作,我们增加的配置内容是非常少而且精简的,对于原有代码的侵入也在忍受范围之内。因此,在构建RESTful API的同时,加入swagger来对API文档进行管理,是个不错的选择。

下面说下在项目使用中遇到的问题:

按照以上demo的配置访问swagger-ui.html是404状态(error:No mapping found for HTTP request with URI [/swagger-ui.html]),最后在github上提的Issues上找到了答案 链接:https://github.com/springfox/springfox/issues/776

问题是15年提的,最后有解决办法,不知道我项目是没配置对还是什么情况用的最新版本的jar没有加载到。解决办法是在Swagger2类加上@EnableWebMv或者继承WebMvcConfigurationSupport然后重写addResourceHandlers()方法解决了加载不到404问题

@Configuration@EnableSwagger2/** * 继承是加路径是无奈之举 默认是不需要继承 * */public class Swagger2 extends WebMvcConfigurationSupport { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors .basePackage("com.ysstech.micro.web")) .paths(PathSelectors.any()).build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("Spring Boot中使用Swagger2构建RESTful APIs") .contact("ysstech").version("1.0").build(); } @Override protected void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/swagger-ui.html").addResourceLocations( "classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**").addResourceLocations( "classpath:/META-INF/resources/webjars/"); }}

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-02-14,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 正文:
  • 添加Swagger2依赖
  • 创建Swagger2配置类
  • 添加文档内容
  • API文档访问与调试
  • 下面说下在项目使用中遇到的问题:
相关产品与服务
Serverless HTTP 服务
Serverless HTTP 服务基于腾讯云 API 网关 和 Web Cloud Function(以下简称“Web Function”)建站云函数(云函数的一种类型)的产品能力,可以支持各种类型的 HTTP 服务开发,实现了 Serverless 与 Web 服务最优雅的结合。用户可以快速构建 Web 原生框架,把本地的 Express、Koa、Nextjs、Nuxtjs 等框架项目快速迁移到云端,同时也支持 Wordpress、Discuz Q 等现有应用模版一键快速创建。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档