SpringMVC和Swagger整合方法 SpringMVC和Swagger整合方法

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

SpringMVC和Swagger整合方法 SpringMVC和Swagger整合方法

pinkylam   2021-03-26 我要评论
想了解SpringMVC和Swagger整合方法的相关内容吗,pinkylam在本文为您仔细讲解SpringMVC和Swagger整合方法的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:springmvc整合swagger,swagger和springmvc,下面大家一起来学习吧。

描述

Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。

总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法、参数和模型紧密集成到服务器端的代码,允许 API 来始终保持同步。Swagger 让部署管理和使用功能强大的 API 从未如此简单。

配置

1、引入相关jar包:

<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>

2、创建java配置类

@Configuration
@EnableSwagger2
public class Swagger2 {
  private ApiInfo apiInfo() {
    return new ApiInfoBuilder()
         // 文档标题
        .title("wish")
        // 文档描述
        .description("https://github.com/handexing").termsOfServiceUrl("https://github.com/handexing")
        .version("v1")
        .build();
  }
  @Bean
  public Docket createRestApi() {
    return new Docket(DocumentationType.SWAGGER_2)
        .apiInfo(apiInfo())
        .select()
        // 指定controller存放的目录路径
        .apis(RequestHandlerSelectors.basePackage("com.wish.controller"))
        .paths(PathSelectors.any())
        .build();
  }
}

3、编写接口文档测试

@RequestMapping(value = "testSawgger", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
@ApiOperation(value = "测试swagger", httpMethod = "POST", notes = "testSawgger")
public ExecuteResult<Boolean> addUser(@ApiParam(value = "参数", required = true) Long id) {
  ExecuteResult<Boolean> result = new ExecuteResult<Boolean>();
  try {
    result.setSuccess(true);
  } catch (Exception e) {
    result.setSuccess(false);
  }
  return result;
}

说明:

@ApiOperation:用在方法之上

1、value: 表示接口名称

2、notes: 表示接口详细描述

3、httpMethod:表示接口请求方法类型

@ApiParam:用在方法参数上

1、required:表示参数是否必须传

2、name:表示参数名称

3、value:表示参数描述

测试

swagger2文档的默认地址是 /swagger-ui.html, 本地开发的访问http://localhost:8080/swagger-ui.html就可以看到自动生成的文档了

结语

到这就配置好了,最终demo可查看 源码地址

总结

以上所述是小编给大家介绍的SpringMVC和Swagger整合方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们