温馨提示×

springboot配置swagger的步骤是什么

小亿
83
2023-11-28 02:55:51
栏目: 编程语言

配置Spring Boot项目使用Swagger的步骤如下:

  1. 添加Swagger依赖:在项目的pom.xml文件中添加Swagger的依赖,例如:
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>
  1. 创建Swagger配置类:创建一个Swagger配置类,用于配置Swagger相关的属性和行为。该类通常使用@Configuration注解进行标记,并使用@EnableSwagger2注解启用Swagger。例如:
@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }
}
  1. 配置Swagger属性:根据需要,可以在Swagger配置类中配置一些Swagger的属性,例如文档标题、描述、版本等。例如:
@Configuration
@EnableSwagger2
public class SwaggerConfig {

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

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("My API Documentation")
                .description("API documentation for my Spring Boot project")
                .version("1.0.0")
                .build();
    }
}
  1. 启动项目并访问Swagger UI:启动Spring Boot应用程序,并通过浏览器访问Swagger UI的URL,通常为http://localhost:8080/swagger-ui.html。在Swagger UI中,您将看到您的API文档和可以测试API的界面。

这些就是配置Spring Boot项目使用Swagger的基本步骤。您还可以根据需要进行更高级的配置,例如按照包或路径筛选API,配置认证等。

0