源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

SpringMVC和Swagger整合方法

  • 时间:2022-10-21 21:44 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:SpringMVC和Swagger整合方法
[b]描述[/b] Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。 总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法、参数和模型紧密集成到服务器端的代码,允许 API 来始终保持同步。Swagger 让部署管理和使用功能强大的 API 从未如此简单。 [b]配置[/b] 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:表示参数描述 [b]测试[/b] swagger2文档的默认地址是 /swagger-ui.html, 本地开发的访问[url=http://localhost:8080/swagger-ui.html]http://localhost:8080/swagger-ui.html[/url]就可以看到自动生成的文档了 [img]http://files.jb51.net/file_images/article/201708/201788142727269.png?201778142746[/img] [b]结语[/b] 到这就配置好了,最终demo可查看 [url=https://github.com/handexing/wish]源码地址[/url] [b]总结[/b] 以上所述是小编给大家介绍的SpringMVC和Swagger整合方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对编程素材网网站的支持!
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部