springboot集成swagger的方法是什么

小億
84
2024-01-24 18:27:48

Spring Boot集成Swagger的方法有以下幾個(gè)步驟:

  1. 引入Swagger相關(guān)依賴:在pom.xml文件中添加以下依賴:
<dependency>
   <groupId>io.springfox</groupId>
   <artifactId>springfox-boot-starter</artifactId>
   <version>3.0.0</version>
</dependency>
  1. 創(chuàng)建Swagger配置類:創(chuàng)建一個(gè)Swagger配置類,用于配置Swagger的相關(guān)信息和規(guī)則。示例代碼如下:
@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket api() { 
        return new Docket(DocumentationType.SWAGGER_2)  
          .select()                                  
          .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))              
          .paths(PathSelectors.any())                          
          .build();
    }
}

在上述代碼中,basePackage方法指定了需要生成API文檔的包路徑,可以根據(jù)實(shí)際情況進(jìn)行修改。

  1. 啟用Swagger:在Spring Boot應(yīng)用主類上使用@EnableSwagger2注解啟用Swagger。示例代碼如下:
@SpringBootApplication
@EnableSwagger2
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
  1. 訪問Swagger UI:?jiǎn)?dòng)Spring Boot應(yīng)用后,可以通過(guò)訪問http://localhost:8080/swagger-ui.html來(lái)查看生成的API文檔。

注意:上述示例中使用的是Swagger 2.x版本,如果使用的是Swagger 3.x版本,需要相應(yīng)地調(diào)整依賴和配置類。

0