要在Spring Boot項目中集成Swagger,你需要遵循以下步驟:
在你的pom.xml文件中添加以下依賴:
<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>
這里我們使用的是2.9.2版本的Swagger,你可以根據需要選擇其他版本。
創建一個名為SwaggerConfig.java的新文件,并添加以下代碼:
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@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();
}
}
在這個配置類中,我們定義了一個名為api的Docket bean。RequestHandlerSelectors.basePackage方法用于指定需要進行Swagger文檔生成的Controller所在的包名。PathSelectors.any()表示所有路徑都需要生成文檔。
啟動你的Spring Boot應用程序,然后在瀏覽器中訪問以下URL:
http://localhost:8080/swagger-ui.html
這里假設你的應用程序運行在8080端口上。你應該能看到Swagger UI界面,其中列出了你的API文檔。
現在你已經成功地將Swagger集成到了你的Spring Boot項目中。你可以使用Swagger UI來測試和瀏覽你的API。