springmvc和swagger整合

作者: 程序员技术客栈 | 来源:发表于2017-08-08 11:36 被阅读420次

描述

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

    本文链接:https://www.haomeiwen.com/subject/jfltrxtx.html