jtlgb

导航

 

Swagger

1、集成springboot

第一步:pom

  <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger2</artifactId>
      <version>2.9.2</version>
  </dependency>
  <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger-ui</artifactId>
      <version>2.9.2</version>
  </dependency>

第二步:swagger在springboot中配置

属性类(省略get/set方法)

/**
 * swagger配置,生成api
 *
 * @author lirui
 * @date 2018-07-26
 */
@ConfigurationProperties(prefix = "hyboot.api")
public class HySwaggerProperties {

    /**
     * 是否开启swagger
     */
    private boolean enabled = false;

    /**
     * API服务标题
     */
    private String title;

    /**
     * API服务描述
     */
    private String description;

    /**
     * API服务版本
     */
    private String version;

    /**
     * Api负责人相关信息
     */
    private Leader leader = new Leader();

    public static class Leader{

        /**
         * 负责人姓名
         */
        private String name;

        /**
         * 负责人邮箱
         */
        private String email;
    }

    /**
     * 用于生成api的html静态文档,需要配置
     */
    private Swagger swagger = new Swagger();

    public static class Swagger{
        /**
         * api 接口获取数据地址
         */
        private String apiUrl;

        /**
         * 生成文件的位置
         */
        private String filePath;
    }
}

配置application.yml

 enabled: false
 title: 测试服务api
 description: 用于测试
 leader:
   name: 汤姆
   email: tom@163.com
 version: 1.0.0

配置类

/**
 * swagger配置,生成api
 *
 * @author lirui
 * @date 2018-07-26
 */
@Configuration
@EnableConfigurationProperties({HySwaggerProperties.class})
@EnableSwagger2
public class HySwaggerAutoConfiguration {

    private Logger logger = LoggerFactory.getLogger(HySwaggerAutoConfiguration.class);
    @Autowired
    private ApplicationContext applicationContext;
    
    @Autowired
    private HySwaggerProperties hySwaggerProperties;
    
    @Autowired
    private ServerProperties serverProperties;

    /**
     * 定义api生成规则
     *
     * @return
     */
    @Bean
    public Docket hyApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                  //group为系统编号(我们spring的id设置为了系统编号)
                .groupName(applicationContext.getId())
                .apiInfo(apiInfo())
                //支持协议
                .protocols(Set.of("http", "https"))
                .select()
                 //限制只有在类上加@Api才添加到swagger,默认是都添加的
                .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
                 //限制只有在方法上加@Api才添加到swagger,默认是都添加的
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .build();
    }

    /**
     * api相关信息
     *
     * @return
     */
    public ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                //服务标题
                .title(hySwaggerProperties.getTitle() == null ?
                    applicationContext.getId() + "系统服务API" :                                                   hySwaggerProperties.getTitle())
                //api服务描述
                .description(hySwaggerProperties.getDescription())
                //api版本
                .version(hySwaggerProperties.getVersion())
                //联系人
                .contact(
                        new Contact(hySwaggerProperties.getLeader().getName(), "",
                                hySwaggerProperties.getLeader().getEmail()))
                .build();
    }
}

第三步:访问

http://host:port/contentPath/swagger-ui.html

1. Swagger是什么?

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

个人觉得,swagger的一个最大的优点是能实时同步api与文档。在项目开发过程中,发生过多次:修改代码但是没有更新文档,前端还是按照老旧的文档进行开发,在联调过程中才发现问题的情况(当然依据开闭原则,对接口的修改是不允许的,但是在项目不稳定阶段,这种情况很难避免)。

2. spring boot 集成 Swagger

目前维护的系统是基于springboot框架开发的,因此本文会详细描述springboot与swagger集成的过程。

spring-boot系统集成swagger需要进行如下操作:

  1. 添加maven依赖,需要在系统的pom中添加如下依赖:

     <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.2.2</version>
     </dependency>
    
  2. 添加swagger配置文件,配置文件如下:

    @Configuration
    @EnableSwagger2
    public class SwaggerConfig {
    
        @Bean
        public Docket api() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .select()  // 选择那些路径和api会生成document
                    .apis(RequestHandlerSelectors.any()) // 对所有api进行监控
                    .paths(PathSelectors.any()) // 对所有路径进行监控
                    .build();
        }
    
    }

    通过注解EnableSwagger2声明Swagger的可用性,此处会定义一个类型为Docket的bean,
    关于docket类的说明如下:

    A builder which is intended to be the primary interface into the swagger-springmvc framework.Provides sensible defaults and convenience methods for configuration.

    Docket的select()方法会提供给swagger-springmvc framework的一个默认构造器(ApiSelectorBuilder),这个构造器为配置swagger提供了一系列的默认属性和便利方法。

  3. 测试

    通过访问:http://localhost:8080/your-app-root/v2/api-docs ,能测试生成的api是否可用。此时返回的是一个json形式的页面,可读性不好。可以通过Swagger UI来生成一个可读性良好的api页面。具体做法就是,在pom中添加相关依赖。如下:

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.2.2</version>
    </dependency>

    再次访问:http://localhost:8080/your-app-root/swagger-ui.html 就可以看到可读性较好的api文档页面。

  4. 注意:

    1. http://localhost:8080/your-app-root/v2/api-docs 中your-app-root指的你的wabapp的根路径,我目前的webapp就默认在根路径下,所以地址是:http://localhost:8080/v2/api-docs
    2. spring-mvc上引用swagger需要做其他相关的配置,具体请查看参考文献
    3. swagger对restful风格的api支持的比较好,非restful风格的api支持的不是很好,对于非restful风格的api或者其他语言(非java语言)可以采用 http://editor.swagger 编辑器来收工完成相关的API编写
posted on 2019-04-01 13:46  jtlgb  阅读(322)  评论(0编辑  收藏  举报