Springfox项目快速入门指南:从零开始构建API文档

Springfox项目快速入门指南:从零开始构建API文档

springfox Automated JSON API documentation for API's built with Spring springfox 项目地址: https://gitcode.com/gh_mirrors/sp/springfox

前言

在现代Web开发中,良好的API文档是项目成功的关键因素之一。Springfox作为一个优秀的Spring生态系统工具,能够自动为基于Spring的应用程序生成美观且实用的API文档。本文将全面介绍如何快速上手Springfox项目,帮助开发者高效构建API文档系统。

一、Springfox简介

Springfox是一个基于Spring框架的API文档生成工具,它能够自动扫描Spring应用程序中的控制器和方法,生成符合OpenAPI/Swagger规范的API文档。主要特点包括:

  • 支持Swagger 2.0和OpenAPI 3.0规范
  • 与Spring Boot无缝集成
  • 自动生成交互式API文档界面
  • 支持多种注解方式定制文档内容

二、环境准备

1. 依赖配置

根据项目构建工具的不同,Springfox提供了多种依赖引入方式:

Gradle配置

稳定版依赖:

repositories {
  jcenter()
}

dependencies {
  // Spring Boot项目
  implementation "io.springfox:springfox-boot-starter:3.0.0"
  
  // 普通Spring MVC项目
  // implementation "io.springfox:springfox-oas:3.0.0"
}

快照版依赖:

repositories {
   maven { url 'http://oss.jfrog.org/artifactory/oss-snapshot-local/' }
}

dependencies {
  // Spring Boot项目
  implementation "io.springfox:springfox-boot-starter:3.0.0-SNAPSHOT"
  
  // 普通Spring MVC项目
  // implementation "io.springfox:springfox-oas:3.0.0-SNAPSHOT"
}
Maven配置

稳定版依赖:

<repositories>
    <repository>
      <id>jcenter-snapshots</id>
      <name>jcenter</name>
      <url>https://jcenter.bintray.com/</url>
    </repository>
</repositories>

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>

快照版依赖:

<repositories>
    <repository>
      <id>jcenter-snapshots</id>
      <name>jcenter</name>
      <url>http://oss.jfrog.org/artifactory/oss-snapshot-local/</url>
    </repository>
</repositories>

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0-SNAPSHOT</version>
</dependency>

三、从2.x版本迁移到3.x

1. Spring Boot应用迁移步骤

  1. 移除旧版本依赖,特别是springfox-swagger2springfox-swagger-ui
  2. 移除@EnableSwagger2注解
  3. 添加springfox-boot-starter依赖
  4. 注意3.x版本移除了对Guava等第三方库的依赖
  5. 如果使用WebMvc但尚未使用@EnableWebMvc注解,需要添加该注解

2. 普通Spring MVC应用迁移步骤

  1. 移除旧版本依赖
  2. 对于OpenAPI添加@EnableOpenApi注解(Swagger 2.0使用@EnableSwagger2
  3. 对于OpenAPI添加springfox-oas依赖(Swagger 2.0使用springfox-swagger2
  4. 同样需要注意Guava相关代码的迁移

3. Swagger UI的变化

  • 对于非Boot应用,springfox-swagger-ui不再通过简单添加依赖自动启用
  • Swagger UI访问路径从/swagger-ui.html变为/swagger-ui/index.html或简写为/swagger-ui/

四、快速入门示例

1. Spring Boot基础配置

@SpringBootApplication
@EnableSwagger2
@ComponentScan(basePackages = {"com.example.controllers"})
public class Swagger2SpringBoot {
    public static void main(String[] args) {
        SpringApplication.run(Swagger2SpringBoot.class, args);
    }

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.any())
            .paths(PathSelectors.any())
            .build()
            .pathMapping("/")
            .directModelSubstitute(LocalDate.class, String.class)
            .genericModelSubstitutes(ResponseEntity.class)
            .useDefaultResponseMessages(false)
            .securitySchemes(newArrayList(apiKey()))
            .securityContexts(newArrayList(securityContext()))
            .enableUrlTemplating(true)
            .globalOperationParameters(
                newArrayList(new ParameterBuilder()
                    .name("someGlobalParameter")
                    .description("Description of someGlobalParameter")
                    .modelRef(new ModelRef("string"))
                    .parameterType("query")
                    .required(true)
                    .build()));
    }

    private ApiKey apiKey() {
        return new ApiKey("mykey", "api_key", "header");
    }

    private SecurityContext securityContext() {
        return SecurityContext.builder()
            .securityReferences(defaultAuth())
            .forPaths(PathSelectors.regex("/anyPath.*"))
            .build();
    }

    List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope
            = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        return newArrayList(
            new SecurityReference("mykey", authorizationScopes));
    }
}

2. 配置详解

  1. @EnableSwagger2:启用Swagger 2.0支持
  2. @ComponentScan:指定控制器扫描路径
  3. Docket:Springfox的主要API配置机制
  4. select():返回ApiSelectorBuilder实例,用于精细控制暴露的端点
  5. apis():使用谓词选择RequestHandler,内置多种谓词如anynone
  6. paths():使用谓词选择Path,支持正则、ant等匹配方式
  7. build():在配置完API和路径选择器后构建选择器
  8. pathMapping():添加servlet路径映射
  9. directModelSubstitute():模型属性替换规则
  10. genericModelSubstitutes():泛型类型替换规则
  11. useDefaultResponseMessages():是否使用默认HTTP响应码
  12. securitySchemes():设置安全方案
  13. securityContexts():设置安全上下文
  14. enableUrlTemplating():启用URL模板支持
  15. globalOperationParameters():添加全局操作参数

五、高级功能扩展

1. Spring Data Rest支持

从2.6.0版本开始,Springfox添加了对Spring Data Rest的支持:

Gradle配置:

dependencies {
    implementation "io.springfox:springfox-data-rest:3.0.0"
}

Java配置:

@Import({... springfox.documentation.spring.data.rest.configuration.SpringDataRestConfiguration.class, ...})

2. JSR-303验证支持

从2.3.2版本开始支持Bean验证注解:

Gradle配置:

dependencies {
    implementation "io.springfox:springfox-bean-validators:3.0.0"
}

Java配置:

@Import({... springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration.class, ...})

3. Swagger UI集成

添加Swagger UI支持:

dependencies {
    compile 'io.springfox:springfox-swagger-ui:3.0.0'
}

集成后,Swagger UI界面默认访问路径为/swagger-ui/index.html

六、安全配置建议

在实际生产环境中,建议对Swagger UI进行安全保护。以下是一个基于Spring Security的配置示例:

protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
        .antMatchers("/swagger-ui/**").authenticated()
        .and().formLogin()
        .and().logout()
        .and().csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
}

结语

Springfox为Spring应用程序提供了强大而灵活的API文档生成能力。通过本文的介绍,开发者应该能够快速上手并配置适合自己项目的文档系统。随着项目的演进,Springfox还提供了更多高级定制选项,可以根据实际需求进行深入探索和配置。

springfox Automated JSON API documentation for API's built with Spring springfox 项目地址: https://gitcode.com/gh_mirrors/sp/springfox

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

强美玮Quincy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值