首页 > 编程 > Java > 正文

SpringMVC和Swagger整合方法

2019-11-26 11:41:56
字体:
来源:转载
供稿:网友

描述

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@EnableSwagger2public 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整合方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持!

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表