Spring Boot整合Swagger2

网络安全守护者 2021-01-20 ⋅ 23 阅读

前言

近年来,随着微服务架构的流行,越来越多的开发人员开始采用Spring Boot作为其微服务的开发框架。而Swagger2作为一种常用的API文档工具,可以帮助开发者更好地管理和测试API接口。在本文中,将介绍如何在Spring Boot项目中整合Swagger2,并且美化Swagger2的标题。

步骤

1. 添加Swagger2依赖

pom.xml文件中添加Swagger2的依赖:

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

2. 创建Swagger2配置类

在项目的config包下创建一个SwaggerConfig类,并添加如下代码:

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.controller"))
                .paths(PathSelectors.any())
                .build();
    }
}

其中,RequestHandlerSelectors.basePackage()方法用于指定需要生成API文档的包路径。

3. 启动Spring Boot项目

运行Spring Boot项目,并在浏览器中访问Swagger2的UI界面:http://localhost:8080/swagger-ui.html。此时应该能看到自动生成的API文档。

4. 美化标题

默认情况下,Swagger2的标题显示为api,我们可以通过修改Swagger2配置类来自定义标题。在SwaggerConfig类中,添加以下代码:

@Bean
public UiConfiguration uiConfig() {
    return UiConfigurationBuilder.builder()
            .docExpansion(DocExpansion.LIST)
            .defaultModelExpandDepth(0)
            .defaultModelRendering(ModelRendering.MODEL)
            .displayOperationId(false)
            .build();
}

@Bean
public Docket api() {
    return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(apiInfo())
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.example.controller"))
            .paths(PathSelectors.any())
            .build();
}

private ApiInfo apiInfo() {
    return new ApiInfoBuilder()
            .title("我的API文档")
            .description("这是一个API文档示例")
            .version("1.0")
            .build();
}

以上代码中,apiInfo()方法用于设置标题、描述和版本信息。

5. 重新启动项目

重启Spring Boot项目后,访问Swagger2的UI界面:http://localhost:8080/swagger-ui.html。此时应该能看到自定义的标题和描述。

总结

通过本文的介绍,我们了解了如何在Spring Boot项目中整合Swagger2,并且通过自定义配置类的方式美化了Swagger2的标题。Swagger2可以帮助我们更加方便地管理和测试API接口,提高开发效率。欢迎大家尝试使用Swagger2来构建自己的API文档!


全部评论: 0

    我有话说: