优雅的配置(升级)swagger3

本文介绍了如何在SpringBoot项目中将Swagger2升级到Swagger3,包括依赖更新、配置类修改,以及如何在生产环境中禁用Swagger。此外,还展示了如何使用Knife4j美化Swagger3的UI界面,提供更友好的文档体验。

Swagger目前最新版本是3.0.0,在Spring Boot应用中集成Swagger3比老的Swagger2简单的多。

以下讲解 适用于swagger2升级swagger3,及新版本直接采用swagger3的项目~

作者现有的项目采用的是swagger2,升级swagger3的时候顺便学习了下。

swagger3配置项

1.依赖项

3的依赖相比2略有不同,不过都是springfox家的,由于springfox家的swagger3兼容swagger2的注解,所以这里升级使用的是springfox实现的swagger3!还有一个springdoc实现的是不兼容的!注意。

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

2.swagger配置类

@Configuration
//@EnableSwagger2 //swagger3版本不需要使用这个注解,当然写上也无所谓~
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.OAS_30)  // swagger2版本这里是DocumentationType.SWAGGER_2
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("xxx管理平台")
                .description("xxx管理平台 API接口文档")
                .license("xxx有限公司")
                .licenseUrl("xxx")
                .version("1.0")
                .build();
    }
}

这里要修改一处,就是把DocumentationType.SWAGGER_2修改为DocumentationType.OAS_30

至于有的教程说还要开启注解@EnableOpenApi,或者@EnableSwagger2,完全不需要。

这里要提到一位作者,比较详细的讲了为啥不需要写注解的原因,详情不在多做描述:传送门 感谢~。这篇文章讲到swagger3是全自动的集成,所以配置项会少的可怜。

3.在生产版本禁用swagger3

在swagger3的源码里有这样一段代码:

@Configuration
@EnableConfigurationProperties(SpringfoxConfigurationProperties.class)
@ConditionalOnProperty(value = "springfox.documentation.enabled", havingValue = "true", matchIfMissing = true)
@Import({
    OpenApiDocumentationConfiguration.class,
    SpringDataRestConfiguration.class,
    BeanValidatorPluginsConfiguration.class,
    Swagger2DocumentationConfiguration.class,
    SwaggerUiWebFluxConfiguration.class,
    SwaggerUiWebMvcConfiguration.class
})
@AutoConfigureAfter({ WebMvcAutoConfiguration.class, JacksonAutoConfiguration.class,
    HttpMessageConvertersAutoConfiguration.class, RepositoryRestMvcAutoConfiguration.class })
public class OpenApiAutoConfiguration {

}

我们找到了关键的一个地方

@ConditionalOnProperty(value = "springfox.documentation.enabled", havingValue = "true", matchIfMissing = true)

@ConditionalOnProperty注解声明了当springfox.documentation.enabled为true时启用配置,而且默认值就是true。这非常有用,Swagger仅仅建议在开发阶段使用,这个正好是个开关。另外我们自定义配置的时候最好把这个开关也加上,通过在配置文件中写上springfox.documentation.enabled=false来在生成版本中禁用swagger3!

springfox.documentation.enabled=false

4.路径放行

如果使用了拦截器或者spring security则需要放行一些swagger必要的路径。

@Override
    public void configure(WebSecurity web) {
        //忽略swagger3所需要用到的静态资源,允许访问
        String[] swaggerUrl = new String[]{
                "/swagger-ui/**",
                "/swagger-resources/**",
                "/v2/api-docs",
                "/v3/api-docs",
                "/webjars/**",                
        };
        web.ignoring().antMatchers(swaggerUrl);
    }

到这里就可以成功访问swaggerUI了。

注意:swagger3和swagger2访问路径不同,swagger2:/swagger-ui.html ,swagger3: /swagger-ui/

如图

 美化swagger

swagger3配置成功了,显然它的界面和swagger2差别并不大,接下来,学习,美化swaggerUI界面。

Knife4j的前身是swagger-bootstrap-ui,前身swagger-bootstrap-ui是一个纯swagger-uiui皮肤项目。

1.下载依赖项

        <dependency>
            <groupId>com.github.shijingsh</groupId>
            <artifactId>knife4j-spring-boot-starter</artifactId>
            <version>3.0.5</version>
        </dependency>

这里要移除掉swagger3的依赖,因为knife4j已经集成swagger3了,为了防止产生不必要的错误。

2.路径放行

String[] swaggerUrl = new String[]{
                "/swagger-ui/**",
                "/swagger-resources/**",
                "/v2/api-docs",
                "/v3/api-docs",
                "/webjars/**",
                "/doc.html",  // 在原有的swagger3放行基础上加上 /doc.html
        };

3.在生产版本禁用swagger3

knife4j:
  # 开启增强配置
  enable: true
  # 开启生产环境屏蔽
  production: true

swagger配置类不用修改,直接访问页面:/doc.html

这里贴一下官方的图,vue风格的ui界面就出来了!

更多的配置项可以查看官方文档:传送门

### 如何使用或配置 Swagger 3 UI Swagger 3 UI 是基于 OpenAPI Specification (OAS) 的工具集合,用于动态生成优雅的 API 文档界面。以下是关于如何安装和配置 Swagger 3 UI 的详细说明。 #### 配置环境 为了成功集成并运行 Swagger 3 UI,需要先确认项目的开发框架支持 OAS 或者 Swagger 规范。常见的后端框架如 Spring Boot 和 Flask 均有对应的插件来简化这一过程[^1]。 --- #### 对于 Spring Boot 用户 在 Spring Boot 中启用 Swagger 3 UI 可通过引入 `springdoc-openapi` 库实现。这是一个专门为 Spring Boot 设计的支持 OpenAPI 3.x 版本的库。 ##### Maven 依赖项 需在项目的 `pom.xml` 文件中添加以下依赖: ```xml <dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-ui</artifactId> <version>1.7.0</version> </dependency> ``` ##### 启动类注解 确保启动类上已标注 `@SpringBootApplication` 注解即可自动加载 Swagger 功能。如果遇到无法访问 `/swagger-ui.html` 页面的情况,则可能是因为误加了某些全局拦截器或者启用了 `@EnableWebMvc` 导致默认路径被覆盖[^3]。 解决方法如下: - 移除不必要的 `@EnableWebMvc` 注解; - 自定义 Swagger 路径映射(仅当确实需要更改默认行为时才执行此操作)。 --- #### 对于 Flask 用户 对于 Python 开发人员而言,可以借助 `flask-swagger-ui` 插件快速完成集成工作。该模块提供了一种简便的方式将 Swagger UI 添加到现有的 Flask Web 应用程序当中[^2]。 ##### 安装命令 通过 pip 工具安装所需包: ```bash pip install flask_swagger_ui ``` ##### 初始化设置 下面是一个简单的例子展示如何初始化以及挂载 Swagger UI 到指定 URL 上面去: ```python from flask import Flask import flask_swagger_ui app = Flask(__name__) # 加载 Swagger UI 所需资源文件夹位置 SWAGGER_URL = &#39;/swagger&#39; API_URL = &#39;http://petstore.swagger.io/v2/swagger.json&#39; # 将 Swagger UI 绑定至应用实例对象之上 swaggerui_blueprint = flask_swagger_ui.get_swaggerui_blueprint( SWAGGER_URL, API_URL, config={ &#39;app_name&#39;: "Test application" } ) app.register_blueprint(swaggerui_blueprint, url_prefix=SWAGGER_URL) ``` 以上脚本会使得用户能够经由浏览器打开 `{host}/swagger` 地址查看文档内容。 --- #### 访问与验证 无论采用哪种技术栈构建服务端逻辑部分,最终都可以通过浏览器输入类似这样的链接形式来进行测试: - **Spring Boot**: http://localhost:8080/swagger-ui/index.html#/ - **Flask**: http://localhost:5000/swagger 此时应该可以看到一个交互式的网页版面呈现出来所有的 RESTful 接口详情描述信息。 --- ### 注意事项 - 如果项目中有安全机制(比如认证授权),则需要额外处理跨域资源共享(CORS),以便前端能正常请求数据。 - 当升级第三方组件版本号之后记得重新审视官方文档是否存在新的改动点影响现有功能正常使用情况。 ---
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值