Spring MVC集成Swagger生成API在线文档


Spring MVC集成Swagger生成API在线文档

一、Swagger 和 Springfox-swagger

1、什么是 Swagger

Swagger 官网:https://swagger.io/

Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端的代码,允许 API 来始终保持同步。Swagger 让部署管理和使用功能强大的 API 从未如此简单。

今天的 Swagger 是由最初 Swagger 规范背后的团队创建的,该规范后来被重新命名为 OpenAPI 规范( OpenAPI Specification,OAS )。今天,Swagger 已经发展成为使用 OAS 开发 api 的最广泛使用的开源工具集之一。

OSA 本身是一个 API 规范,它用于描述一整套 API 接口,包括一个接口是 GET 还是 POST 请求啊,有哪些参数哪些 header 啊,都会被包括在这个文件中。它在设计的时候通常是 YAML 格式,这种格式书写起来比较方便,而在网络中传输时又会以 json 形式居多,因为 json 的通用性比较强。

简单说来主要有两个功能:API 接口文档在线自动生成和 API 调用调试。

2、什么是 Springfox-swagger

由于 Spring 的流行,Marty Pitt 编写了一个基于 Spring 的组件swagger-springmvc,用于将 swagger 集成到 springmvc 中来。而 springfox 则是从这个组件发展而来。

Springfox 同时支持 Swagger 规范的 1.2 版和 2.0 版。

5. Swagger
Springfox supports both version 1.2 and version 2.0 of the Swagger specification. Where possible, the Swagger 2.0 specification is preferable.
The swagger-core annotations, as provided by swagger-core, are typically used to decorate the java source code of an API which is bing ‘swaggered’. Springfox is aware of the Swagger-Core Annotations and will favor those annotations over inferred defaults.
5.1. Swagger 1.2 vs Swagger 2.0
One major difference between the two swagger specification is the composition of the generated swagger documentation.
With Swagger 1.2 an applications API is represented as a Resource Listing and multiple API Declarations which has the implication of producing multiple JSON files
With Swagger 2.0 things are much simpler and an application’s API can be represented in a single JSON file.

http://springfox.github.io/springfox/docs/current/#swagger

本文使用 Swagger 规范 2.0 版的 Springfox-swagger( springfox-swagger2 )。

如果想要集成swagger-springmvc相对麻烦一点,因为要把它的静态文件 copy 到自己的项目中。springfox-swagger2 依然是依赖 OSA 规范文档,也就是一个描述 API 的 json 文件,而这个组件的功能就是帮助我们自动生成这个 json 文件,我们会用到的另外一个组件 springfox-swagger-ui 就是将这个 json 文件解析出来,用一种更友好的方式呈现出来,而不用自己拷贝 swagger ui(https://github.com/swagger-api/swagger-ui)到项目中。

下面,我们进行 SpringMVC 集成 springfox-swagger2 的讲解

二、Spring 项目集成 Springfox-swagger2

1、添加依赖

这里使用 gradle:

compile group: 'io.springfox', name: 'springfox-swagger2', version: '2.9.2'
compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.9.2'
Spring MVC集成Swagger生成API在线文档-打不死的小强

2、配置静态文件可访问

在 springmvc.xml 配置文件添加:

<!--配置 swagger 资源不被拦截-->
<mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/" />
<mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/" />

或者参考:Spring MVC 设置不拦截静态资源 设置。

3、Swagger 配置

新建 SwaggerConfig 类,加入如下代码:

//swagger 交由 spring 管理
@Configuration
//使 swagger 生效
@EnableSwagger2
//@EnableWebMvc
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                //设置只生成被@Api 注解的 Controller 类中有@ApiOperation 注解的 api 接口的文档
                .apis(RequestHandlerSelectors.withClassAnnotation(Api.class)).apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                //.apis(RequestHandlerSelectors.any())
                .build()
                .apiInfo(apiInfo());
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Springfox-swagger2 API")
                //.description("Springfox-swagger2 API 在线文档")
                .version("1.0.0")
                //.termsOfServiceUrl("http://www.lwqgj.cn")
                //.license("")
                //.licenseUrl("")
                .build();
    }
}

这个 SwaggerConfig 类有四个注解,其中,@Configuration 是 Spring 的注解,而@EnableSwagger2 则是用来启动 Swagger2 支持,表示这是一个 Spring Swagger 的配置文件。之后,定义了一个 Bean 方法 api,Spring 中名字并不重要,重要的是它返回一个 Docket 类,DocumentationType.SWAGGER_2 作为 Docket 构造方法的参数,指定了所用的 swagger 版本 2.0。而之后的 apiInfo 则是调用接下来的 apiInfo 函数,来创建 Docket 的信息。apiInfo 函数采用 ApiInfoBuilder 来创建 ApiInfo 类。

然后运行项目,在浏览器输入:http://{ip}:{port}/{projectname}/swagger-ui.html ,注意 swagger-ui.html 是固定写法,实际上它访问的是 springmvc.xml 中指定的springfox-swagger-ui 依赖 jar 中的资源

Spring MVC集成Swagger生成API在线文档-打不死的小强

然后可以看到 swagger ui 页面了:

Spring MVC集成Swagger生成API在线文档-打不死的小强

4、Swagger 接口文档实现

实现 swagger API 文档只需要在 springmvc 的 controller 层类中使用相关注解(@Api、@ApiOperation 等)(或者修改 SwaggerConfig 配置中.select().apis()默认扫描 API 规则)即可自动生成 swagger 在线 API 文档。下面来个栗子:

@RestController
@RequestMapping("/index")
@Api(value = "/index", tags = "接口测试")
public class IndexController {

    @GetMapping(value = "index1", produces = "text/plain; charset=utf-8")
    @ApiOperation(value = "测试", notes = "测试")
    public String index1(){
        return "你好,世界";
    }
}
Spring MVC集成Swagger生成API在线文档-打不死的小强

5、附:swagger 不同 ui

上面使用的 swagger ui 是由springfox-swagger-ui 2.9.2 提供的,个人感觉这个 ui 很丑。 springfox-swagger-ui 从 2.8.0 版本开始使用这个 ui 样式,但我们可以自己选择喜欢的 ui 样式。

(1)springfox-swagger-ui 2.7.0

修改依赖:

//从 springfox-swagger-ui2.8.0 开始,ui 界面发生大的变化,个人感觉新版 ui 很丑
compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.7.0'

效果如下:

Spring MVC集成Swagger生成API在线文档-打不死的小强

(1)swagger-bootstrap-ui

有牛人做了一套全新的 swagger ui。添加依赖:

//比较美观的 swagger-ui
compile group: 'com.github.xiaoymin', name: 'swagger-bootstrap-ui', version: '1.9.4'

该 ui 访问路径为: http://{ip}:{port}/{projectname}/doc.html ,(别忘了,要对 doc.html 放行,参见:Spring MVC 设置不拦截静态资源 )效果如下:

Spring MVC集成Swagger生成API在线文档-打不死的小强

好了,完毕!



发表评论

邮箱地址不会被公开。 必填项已用*标注