Skip to content

07 springfox swagger2

Alan edited this page Apr 13, 2018 · 9 revisions

工具及汇总api转发设计图

工具和api转发设计图

Spring Cloud程序快速接入SpringFox-swagger2

  1. pom.xml中添加依赖
<!-- swagger --> 
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.8.0</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-bean-validators</artifactId>
    <version>2.8.0</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.8.0</version>
</dependency>
  1. 和Application配置启动类同级添加Swagger配置类 参考代码

    需要根据实际情况修改的代码:

    .apis(RequestHandlerSelectors.basePackage("com.demo.controller"))// 扫描该包下的所有需要在Swagger中展示的API,@ApiIgnore注解标注的除外

  2. 文档注解使用参考

    注解使用参考

  3. 关于swaggerui-eureka

    默认情况下,每个微服务暴露的端口下

    会对外提供api访问(http:${host}:${port}/swagger-ui.html);
    会对外提供json格式的openapi spec访问地址(http:${host}:${port}/v2/api-docs).

    这种情况在服务众多的情况下就是个灾难........,虽然swagger-ui可以通过查询openapi spec地址的方式进行显示,但是如果将spec导出那么代码和api又分离了,有违初衷.

    虽然swagger提供了以添加SwaggerResource的方式,在界面上方显示所有服务的spec,但是在使用swagger进行接口测试时,相同的服务将会合并,无法做到针对指定部署到服务的机器发起请求.并且管理所有服务的路由也要耦合到业务网关中.

    基于以上考虑,所以开发了swaggerui-eureka,因为所有微服务都是注册在 eureka上面,且api的地址是有规律可循的,即获取[]微服务实例uri+/swagger-ui.html]即可获取实时的所有在开发/测试环境的api. 如图:(承认较丑,前端有几年没写了,有时间则修好看点....)

    swaggerui-eureka界面展示

Clone this wiki locally