【最新】spring-boot2.0 整合 swagger2 (版本 2.9.2)及注意坑点

文章目录

      • 1. Swagger 简介
      • 2. Swagger 快速集成
      • 3. 注意事项

1. Swagger 简介

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

2. Swagger 快速集成

  • 添加pom依赖
<!-- swagger-ui -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>${swagger-ui.version}</version>
</dependency>

<!-- swagger2 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>${swagger2.version}</version>
</dependency>
<!-- 解决FluentIterable.class找不到问题 -->
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>26.0-jre</version>
</dependency>
<!-- java8 不需要添加,高版本需要添加 -->
<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.3.0</version>
</dependency>
  • 添加配置文件
@Configuration
public class SwaggerConf {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                // 自行修改为自己的包路径
                .apis(RequestHandlerSelectors.basePackage("com.luhanlin"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("api文档")
                .description("restful 风格接口")
                //服务条款网址
                //.termsOfServiceUrl("")
                .version("1.0")
                //.contact(new Contact("hello", "url", "email"))
                .build();
    }

}
  • 启动类中添加 @EnableSwagger2注解,开启swagger;

  • 对接口进行api文档注解,不进行注解也会由相关的api,但是没有接口的详细描述,只有开发人员可以看懂。

  • 在API接口上进行接口的注解以下只是简单的进行API配置,详细注解配置可以查看文本末的参考博文

@ApiOperation(value = "feign远程服务调用测试",notes = "查询test")
@ApiImplicitParam(name = "id",value = "用户id")
@HystrixCommand
@GetMapping(value = "/{id}")
public ResultInfo getTest(@PathVariable("id") Integer id){
    RedisUtil.set("test","123456");
    log.info(">>>>>>>>>> redis 获取 test >>>>>>" + RedisUtil.get("test"));
    Test test = testService.queryTest(id);
    log.info("查询出来的test为: " + test);
    return ResultUtil.success(test);
}
  • 最后启动工程,访问http://localhost:8080/swagger-ui.html可以看到以下API文档:
    -【最新】spring-boot2.0 整合 swagger2 (版本 2.9.2)及注意坑点_第1张图片

3. 注意事项

Spring-boot2.0以上在集成swagger后,配置WebConfig时不要extends WebMvcConfigurationSupport,需要修改为最新的implements WebMvcConfigurer,不然访问http://localhost:8080/swagger-ui.html时读取不到swagger-ui的静态资源文件。

参考博文:Swagger使用指南

Github地址: spring-cloud 基础模块搭建 ---- 欢迎指正

你可能感兴趣的:(java)