Spring Boot & Swagger

本文接着前面的继续,介绍如何快速接入Swagger

  • Spring Boot七分钟快速实践
  • Spring Boot & MyBatis
  • Spring Boot & Redis
  • Spring Boot & Swagger
  • Spring Boot & 单元测试
  • Spring Boot & Actuator
  • Spring Boot Admin

两步接入

  • pom.xml

    io.springfox
    springfox-swagger2
    2.9.2


    io.springfox
    springfox-swagger-ui
    2.9.2

  • 代码配置
@Configuration
@EnableSwagger2
public class SwaggerConfig {                                    
    @Bean
    public Docket api() { 
        return new Docket(DocumentationType.SWAGGER_2)  
          .select()                                  
          .apis(RequestHandlerSelectors.any())              
          .paths(PathSelectors.any())                          
          .build();                                           
    }
}

展示

  • 数据接口
    http://localhost:8080/swagger-ui.html

  • UI
    http://localhost:8080/v2/api-docs

Swagger文档展示

已经实现了最简单的接入了


其他配置

  • 限制开发环境展示
    使用Spring条件注入特性@Profile("dev")
@Configuration
@EnableSwagger2
@Profile("dev")
public class SwaggerConfig {                                    

测试环境启动命令如下

java -jar boot-web-2.1.2.RELEASE.jar -Dspring.profiles.active=dev
  • 限制部分接口
@Bean
public Docket api() {
    return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.tenmao.mvc.controller"))
            .paths(PathSelectors.ant("/api/*"))
            .build();
}
  • 自定义文档信息
@Bean
public Docket api() {
    return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.tenmao.mvc.controller"))
            .paths(PathSelectors.ant("/api/*"))
            .build()
            // 这里有一个调用
            .apiInfo(apiInfo());
}

private ApiInfo apiInfo() {
    return new ApiInfo(
            "十毛API",
            "十毛API文档",
            "1.0",
            "Terms of service",
            new Contact("tenmao", "https://www.jianshu.com/u/518bde83a9bc", "[email protected]"),
            "License of API", "API license URL", Collections.emptyList());
}

SpringBoot入门系列

  • SpringBoot七分钟快速实践
  • SpringBoot & MyBatis
  • SpringBoot & Redis

参考

  • https://www.baeldung.com/swagger-2-documentation-for-spring-rest-api
  • 生产环境中禁用swagger
  • 代码自动生成文档 - Springfox(Swagger2)

你可能感兴趣的:(Spring Boot & Swagger)